diff --git a/CHANGELOG.md b/CHANGELOG.md index cdd9cfb063a..4fea8502482 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: with `serializer.discriminator_map` enabled (Laravel: `api-platform.serializer.discriminator_map`), the subtypes declared in the serializer `#[DiscriminatorMap]` of a resource, or in its Doctrine discriminator map with `doctrine.discriminator_map` / `doctrine_mongodb_odm.discriminator_map`, are read, written and documented. An update never changes the subtype: a `PUT` or `PATCH` with another type, or a JSON-LD `@type` contradicting the type property, returns a 422. A subtype that is not a resource is named after its class short name in JSON-LD and Hydra: declare it as a resource (e.g. `#[ApiResource(operations: [])]`) to give it another name or `types`. GraphQL is not supported yet for these resources: the default GraphQL operations are dropped, explicit `graphQlOperations` throw. With the Doctrine flags the type property is the discriminator column name, declare a serializer `#[DiscriminatorMap]` on the resource to rename it. Off by default ([#8874](https://github.com/api-platform/core/pull/8874)). * GraphQL: properties typed as a list of `bool`, `int`, `float` or `string` are now exposed as `[Boolean]`, `[Int]`, `[Float]` and `[String]` instead of the `Iterable` scalar; dictionaries and lists of other types still use `Iterable`, so schemas and clients using these fields must be updated ([#8619](https://github.com/api-platform/core/pull/8619)). * JSON Schema: properties typed with a PHPDoc `array{...}` shape are now documented as objects with `properties` and `required` instead of a generic object or array ([#8767](https://github.com/api-platform/core/pull/8767)). 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..474ebfe9ad9 --- /dev/null +++ b/src/Doctrine/Common/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoader.php @@ -0,0 +1,158 @@ + + * + * 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 discriminator map (ORM, MongoDB ODM) of a resource hierarchy as a serializer discriminator map. + * + * The serializer does not inherit maps: every class with subclasses gets its own map, so a resource declared in the + * middle of a hierarchy resolves its subtypes too. A serializer map declared in the hierarchy takes precedence. + * + * @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; + } + + $defaultType = null; + if (!(new \ReflectionClass($class))->isAbstract() && false !== $ownType = array_search($class, $typesMapping, true)) { + $defaultType = (string) $ownType; + } + + $classMetadata->setClassDiscriminatorMapping(new ClassDiscriminatorMapping($typeProperty, $typesMapping, $defaultType)); + + 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; + } + + 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..2a2df5917d7 --- /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, 'vehicle'), $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], 'car'), + $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/Hal/Serializer/ItemNormalizer.php b/src/Hal/Serializer/ItemNormalizer.php index b78837b08fc..91c061a9cc3 100644 --- a/src/Hal/Serializer/ItemNormalizer.php +++ b/src/Hal/Serializer/ItemNormalizer.php @@ -19,6 +19,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Metadata\Util\TypeHelper; @@ -56,7 +57,7 @@ final class ItemNormalizer extends AbstractItemNormalizer private array $componentsCache = []; private array $attributesMetadataCache = []; - public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null) + public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, ?SubtypeResolverInterface $subtypeResolver = null) { $defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] = function ($object): ?array { $iri = $this->iriConverter->getIriFromResource($object); @@ -67,7 +68,7 @@ public function __construct(PropertyNameCollectionFactoryInterface $propertyName return ['_links' => ['self' => ['href' => $iri]]]; }; - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); } /** diff --git a/src/Hal/composer.json b/src/Hal/composer.json index 99b6e73788c..c098ce9cd08 100644 --- a/src/Hal/composer.json +++ b/src/Hal/composer.json @@ -23,9 +23,9 @@ "require": { "php": ">=8.2", "api-platform/state": "^5.0", - "api-platform/metadata": "^5.0", + "api-platform/metadata": "^5.1", "api-platform/documentation": "^5.0", - "api-platform/serializer": "^5.0", + "api-platform/serializer": "^5.1", "symfony/type-info": "^7.4 || ^8.0" }, "autoload": { diff --git a/src/Hydra/Serializer/DocumentationNormalizer.php b/src/Hydra/Serializer/DocumentationNormalizer.php index 3492403a94d..3a7a0135198 100644 --- a/src/Hydra/Serializer/DocumentationNormalizer.php +++ b/src/Hydra/Serializer/DocumentationNormalizer.php @@ -17,6 +17,7 @@ use ApiPlatform\JsonLd\ContextBuilder; use ApiPlatform\JsonLd\ContextBuilderInterface; use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait; +use ApiPlatform\JsonLd\SubtypePropertyScopeTrait; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\CollectionOperationInterface; @@ -28,6 +29,7 @@ use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\TypeHelper; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; @@ -48,6 +50,7 @@ final class DocumentationNormalizer implements NormalizerInterface { use HydraPrefixTrait; + use SubtypePropertyScopeTrait; public const FORMAT = 'jsonld'; public function __construct( @@ -59,6 +62,7 @@ public function __construct( private readonly ?NameConverterInterface $nameConverter = null, private readonly ?array $defaultContext = [], private readonly ?bool $entrypointEnabled = true, + private readonly ?SubtypeResolverInterface $subtypeResolver = null, ) { } @@ -68,8 +72,12 @@ public function __construct( public function normalize(mixed $data, ?string $format = null, array $context = []): array { $classes = []; + $classIndexes = []; + $subtypeClasses = []; + $resourceParents = []; $entrypointProperties = []; $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext); + $resourceClasses = array_fill_keys(iterator_to_array($data->getResourceNameCollection(), false), true); foreach ($data->getResourceNameCollection() as $resourceClass) { $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass); @@ -84,10 +92,108 @@ 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); + $classIndexes[$resourceClass][] = array_key_last($classes); + + if (!$this->subtypeResolver?->getDirectSubtypes($resourceClass)) { + continue; + } + + [$propertyNameContext, $propertyContext] = $this->getPropertyMetadataFactoryContext($resourceMetadata); + $propertyNames = iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $propertyNameContext), false); + $mapping = $this->subtypeResolver->getMapping($resourceClass); + if (null !== $mapping && !\in_array($mapping->getTypeProperty(), $propertyNames, true)) { + $classes[array_key_last($classes)][$hydraPrefix.'supportedProperty'][] = $this->getTypeProperty($resourceClass, $prefixedShortName, $shortName, $context, $hydraPrefix); + } + + $scopes = $this->getSubtypePropertyScopes($this->subtypeResolver, $this->propertyMetadataFactory, $resourceClass, $propertyNames, fn (string $class): array => iterator_to_array($this->propertyNameCollectionFactory->create($class, $propertyNameContext), false)); + $this->addSubtypeClasses($subtypeClasses, $resourceParents, $resourceClasses, $resourceClass, $prefixedShortName, $scopes, $propertyContext, $context, $hydraPrefix); } } - return $this->computeDoc($data, $this->getClasses($entrypointProperties, $classes, $hydraPrefix), $hydraPrefix); + foreach ($resourceParents as $resourceClass => $parents) { + foreach ($classIndexes[$resourceClass] ?? [] as $index) { + $subClassOf = array_values(array_unique([...(array) ($classes[$index]['subClassOf'] ?? []), ...$parents])); + $classes[$index]['subClassOf'] = 1 === \count($subClassOf) ? $subClassOf[0] : $subClassOf; + } + } + + return $this->computeDoc($data, $this->getClasses($entrypointProperties, [...$classes, ...array_values($subtypeClasses)], $hydraPrefix), $hydraPrefix); + } + + /** + * Documents the subtypes of a discriminator map as subclasses of their parent, supporting the properties they declare. + * + * @param array> $subtypeClasses + * @param array> $resourceParents + * @param array $resourceClasses + * @param array{array>, array>, array>} $scopes + */ + private function addSubtypeClasses(array &$subtypeClasses, array &$resourceParents, array $resourceClasses, string $class, string $classId, array $scopes, array $propertyContext, array $context, string $hydraPrefix): void + { + [$propertyScopes, $iris, $typeProperties] = $scopes; + foreach ($this->subtypeResolver?->getDirectSubtypes($class) ?? [] as $subtype) { + if (isset($resourceClasses[$subtype])) { + $resourceParents[$subtype][] = $classId; + + continue; + } + + $subtypeId = $this->getClassId($subtype); + if (isset($subtypeClasses[$subtypeId])) { + continue; + } + + $properties = []; + foreach ($propertyScopes[$subtype] ?? [] as $propertyName => $scope) { + $scopeId = $this->getClassId($scope); + $scopeName = $this->subtypeResolver->getTypeName($scope); + if (isset($typeProperties[$subtype][$propertyName])) { + $properties[] = $this->getTypeProperty($subtype, $scopeId, $scopeName, $context, $hydraPrefix); + + continue; + } + + $propertyMetadata = $this->propertyMetadataFactory->create($subtype, $propertyName, $propertyContext); + if ((true === $propertyMetadata->isIdentifier() && false === $propertyMetadata->isWritable()) || false === $propertyMetadata->getHydra()) { + continue; + } + + if (isset($iris[$propertyName])) { + $propertyMetadata = $propertyMetadata->withIris($iris[$propertyName]); + } + + $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $subtype, self::FORMAT, $context) : $propertyName; + $properties[] = $this->getProperty($propertyMetadata, $normalizedPropertyName, $scopeId, $scopeName, $hydraPrefix); + } + + $subtypeClasses[$subtypeId] = [ + '@id' => $subtypeId, + '@type' => $hydraPrefix.'Class', + $hydraPrefix.'title' => $this->subtypeResolver->getTypeName($subtype), + 'subClassOf' => $classId, + $hydraPrefix.'supportedProperty' => $properties, + $hydraPrefix.'supportedOperation' => [], + ]; + + $this->addSubtypeClasses($subtypeClasses, $resourceParents, $resourceClasses, $subtype, $subtypeId, $scopes, $propertyContext, $context, $hydraPrefix); + } + } + + private function getClassId(string $class): string + { + return '#'.$this->subtypeResolver?->getTypeName($class); + } + + /** + * The type property of a discriminator map is not a property of the class, it is documented as one. + */ + private function getTypeProperty(string $class, string $classId, string $shortName, array $context, string $hydraPrefix): array + { + $mapping = $this->subtypeResolver?->getMapping($class); + $typeProperty = $mapping?->getTypeProperty() ?? ''; + $propertyMetadata = (new ApiProperty())->withNativeType(Type::string())->withReadable(true)->withWritable(true)->withRequired(null === $mapping?->getDefaultType()); + + return $this->getProperty($propertyMetadata, $this->nameConverter?->normalize($typeProperty, $class, self::FORMAT, $context) ?? $typeProperty, $classId, $shortName, $hydraPrefix); } /** diff --git a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php index b83dbdcd8e2..2b7ed61c548 100644 --- a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php +++ b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php @@ -28,14 +28,18 @@ use ApiPlatform\Metadata\Property\PropertyNameCollection; use ApiPlatform\Metadata\Put; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; use ApiPlatform\Metadata\Resource\ResourceNameCollection; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolver; use ApiPlatform\Metadata\UrlGeneratorInterface; use PHPUnit\Framework\Attributes\IgnoreDeprecations; 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 +1216,89 @@ public function testNormalizeWithStringGroups(): void $this->assertSame('#dummy', $doc['hydra:supportedClass'][0]['@id']); $this->assertNotEmpty($doc['hydra:supportedClass'][0]['hydra:supportedProperty']); } + + public function testSubtypesAreDocumentedAsSubclasses(): void + { + $resourceNames = new ResourceNameCollection([HydraDiscriminatedVehicle::class, HydraDiscriminatedBus::class]); + $documentation = new Documentation($resourceNames, 'Test Api', 'test', '0.0.0'); + + $propertyNames = [ + HydraDiscriminatedVehicle::class => ['name'], + HydraDiscriminatedCar::class => ['name', 'doors'], + HydraDiscriminatedTruck::class => ['name', 'payload'], + HydraDiscriminatedHeavyTruck::class => ['name', 'payload', 'axles'], + HydraDiscriminatedBus::class => ['name', 'seats'], + ]; + $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 { + $shortName = HydraDiscriminatedBus::class === $class ? 'HydraDiscriminatedBus' : '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, 'bus' => HydraDiscriminatedBus::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); + + $resourceNameCollectionFactory = $this->createStub(ResourceNameCollectionFactoryInterface::class); + $resourceNameCollectionFactory->method('create')->willReturn($resourceNames); + $subtypeResolver = new SubtypeResolver($classDiscriminatorResolver, $resourceNameCollectionFactory, $resourceMetadataFactory); + + $documentationNormalizer = new DocumentationNormalizer($resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, $resourceClassResolver, $urlGenerator, null, [], true, $subtypeResolver); + + $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', '#HydraDiscriminatedBus', '#HydraDiscriminatedCar', '#HydraDiscriminatedTruck', '#HydraDiscriminatedHeavyTruck'], array_column($classes, '@id')); + + // The type property of a map is supported by the class declaring the map + $this->assertSame(['#HydraDiscriminatedVehicle/name', '#HydraDiscriminatedVehicle/kind'], $properties($classes[0])); + + // A subtype that is a resource keeps its own class + $this->assertSame('#HydraDiscriminatedVehicle', $classes[1]['subClassOf']); + + $this->assertSame('#HydraDiscriminatedVehicle', $classes[2]['subClassOf']); + $this->assertSame(['#HydraDiscriminatedCar/doors'], $properties($classes[2])); + + $this->assertSame('#HydraDiscriminatedVehicle', $classes[3]['subClassOf']); + $this->assertSame(['#HydraDiscriminatedTruck/payload', '#HydraDiscriminatedTruck/size'], $properties($classes[3])); + + $this->assertSame('#HydraDiscriminatedTruck', $classes[4]['subClassOf']); + $this->assertSame(['#HydraDiscriminatedHeavyTruck/axles'], $properties($classes[4])); + } +} + +class HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedCar extends HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedTruck extends HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedHeavyTruck extends HydraDiscriminatedTruck +{ +} + +class HydraDiscriminatedBus extends HydraDiscriminatedVehicle +{ } diff --git a/src/Hydra/composer.json b/src/Hydra/composer.json index f7b66761dbb..d4ab900a7df 100644 --- a/src/Hydra/composer.json +++ b/src/Hydra/composer.json @@ -27,8 +27,8 @@ "php": ">=8.2", "api-platform/state": "^5.0", "api-platform/documentation": "^5.0", - "api-platform/metadata": "^5.0", - "api-platform/jsonld": "^5.0", + "api-platform/metadata": "^5.1", + "api-platform/jsonld": "^5.1", "api-platform/json-schema": "^5.0", "api-platform/serializer": "^5.0", "symfony/web-link": "^7.4 || ^8.0", diff --git a/src/JsonApi/JsonSchema/SchemaFactory.php b/src/JsonApi/JsonSchema/SchemaFactory.php index 717a5b39723..23d5ab3ed43 100644 --- a/src/JsonApi/JsonSchema/SchemaFactory.php +++ b/src/JsonApi/JsonSchema/SchemaFactory.php @@ -27,6 +27,7 @@ use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\State\ApiResource\Error; /** @@ -81,7 +82,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 ?SubtypeResolverInterface $subtypeResolver = null) { if (!$definitionNameFactory) { $this->definitionNameFactory = new DefinitionNameFactory(); @@ -291,7 +292,15 @@ private function buildDefinitionPropertiesSchema(string $key, string $documentDe // 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->subtypeResolver?->getMapping($propertyClass) ? $definitions[$key]['oneOf'] ?? [] : [] as $branch) { + if (!isset($branch['$ref'])) { + $ownBranch = $branch; + break; + } + } + $properties = $ownBranch['properties'] ?? $definitions[$key]['properties'] ?? []; $attributes = []; $relationships = []; @@ -383,18 +392,111 @@ 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()) 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.'.'.$this->subtypeResolver->getTypeName($subClass); + $subSchema = $this->buildDefinitionPropertiesSchema($subKey, $subDocumentDefinitionName, $subClass, $format, $type, $resourceOperation, $schema, $serializerContext); + 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; } + /** + * Matches the "$ref" branches of a "oneOf" to the subtypes through the type value their definition declares. + * + * @return iterable + */ + private function getDiscriminatedSubtypes(string $key, string $className, \ArrayObject $definitions, string $version): iterable + { + if (!isset($definitions[$key]['oneOf']) || null === $mapping = $this->subtypeResolver?->getMapping($className)) { + return; + } + + $typeProperty = $mapping->getTypeProperty(); + $subtypes = $this->subtypeResolver->getDirectSubtypes($className); + $prefix = $this->getSchemaUriPrefix($version); + foreach ($definitions[$key]['oneOf'] as $branch) { + if (!isset($branch['$ref'])) { + continue; + } + + $subKey = substr($branch['$ref'], \strlen($prefix)); + $typeValue = $this->getTypeValue($definitions, $subKey, $typeProperty, $prefix); + if (null !== $typeValue && isset($subtypes[$typeValue])) { + yield [$subKey, $subtypes[$typeValue], $typeProperty]; + } + } + } + + private function getTypeValue(\ArrayObject $definitions, string $key, string $typeProperty, string $prefix): ?string + { + if (isset($definitions[$key]['properties'][$typeProperty]['enum'][0])) { + return (string) $definitions[$key]['properties'][$typeProperty]['enum'][0]; + } + + foreach ($definitions[$key]['oneOf'] ?? [] as $branch) { + $typeValue = isset($branch['$ref']) ? $this->getTypeValue($definitions, substr($branch['$ref'], \strlen($prefix)), $typeProperty, $prefix) : ($branch['properties'][$typeProperty]['enum'][0] ?? null); + if (null !== $typeValue) { + return (string) $typeValue; + } + } + + return null; + } + private function getRelationship(string $resourceClass, string $property, ?array $serializerContext): ?array { $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property, $serializerContext ?? []); @@ -409,6 +511,10 @@ private function getRelationship(string $resourceClass, string $property, ?array $relatedClasses = []; foreach ($relationships as [$className, $isCollection]) { $isOne = $isOne || !$isCollection; + // A relation narrowed to a subtype targets the resource itself + if (null !== $this->subtypeResolver) { + $className = $this->resourceClassResolver->getResourceClass(null, $className); + } $relatedClasses[$className] = $className; } diff --git a/src/JsonApi/Serializer/ItemDenormalizer.php b/src/JsonApi/Serializer/ItemDenormalizer.php index 8ed3a0ac319..4725c0e4601 100644 --- a/src/JsonApi/Serializer/ItemDenormalizer.php +++ b/src/JsonApi/Serializer/ItemDenormalizer.php @@ -19,6 +19,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Serializer\AbstractItemNormalizer; use ApiPlatform\Serializer\OperationResourceClassResolverInterface; use ApiPlatform\Serializer\TagCollectorInterface; @@ -53,8 +54,9 @@ public function __construct( protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, private readonly bool $useIriAsId = true, + ?SubtypeResolverInterface $subtypeResolver = null, ) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); } public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool diff --git a/src/JsonApi/Serializer/ItemNormalizer.php b/src/JsonApi/Serializer/ItemNormalizer.php index aafd45f2a99..df84efb8cd6 100644 --- a/src/JsonApi/Serializer/ItemNormalizer.php +++ b/src/JsonApi/Serializer/ItemNormalizer.php @@ -22,6 +22,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Metadata\Util\CompositeIdentifierParser; @@ -89,8 +90,9 @@ public function __construct( private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null, bool $useIriAsId = true, ?ResourceLinkageResolver $resourceLinkageResolver = null, + ?SubtypeResolverInterface $subtypeResolver = null, ) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); $this->useIriAsId = $useIriAsId; $this->resourceLinkageResolver = $resourceLinkageResolver ?? new ResourceLinkageResolver($resourceClassResolver); } diff --git a/src/JsonApi/composer.json b/src/JsonApi/composer.json index 27bc2a4e5a3..87ea5ac978a 100644 --- a/src/JsonApi/composer.json +++ b/src/JsonApi/composer.json @@ -24,8 +24,8 @@ "php": ">=8.2", "api-platform/documentation": "^5.0", "api-platform/json-schema": "^5.0", - "api-platform/metadata": "^5.0", - "api-platform/serializer": "^5.0.6", + "api-platform/metadata": "^5.1", + "api-platform/serializer": "^5.1", "api-platform/state": "^5.0", "symfony/error-handler": "^7.4 || ^8.0", "symfony/http-foundation": "^7.4 || ^8.0", diff --git a/src/JsonLd/ContextBuilder.php b/src/JsonLd/ContextBuilder.php index 82f90e6f21b..6328107f6f4 100644 --- a/src/JsonLd/ContextBuilder.php +++ b/src/JsonLd/ContextBuilder.php @@ -14,6 +14,7 @@ namespace ApiPlatform\JsonLd; use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait; +use ApiPlatform\Metadata\Exception\RuntimeException; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\HttpOperation; use ApiPlatform\Metadata\IriConverterInterface; @@ -22,6 +23,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; @@ -35,12 +37,13 @@ final class ContextBuilder implements AnonymousContextBuilderInterface, Operatio { use ClassInfoTrait; use HydraPrefixTrait; + use SubtypePropertyScopeTrait; public const FORMAT = 'jsonld'; 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 ?SubtypeResolverInterface $subtypeResolver = null) { } @@ -234,40 +237,89 @@ 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; - } + if (null === $this->subtypeResolver) { + return $context; + } - $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName; - $jsonldContext = $propertyMetadata->getJsonldContext() ?? []; + $this->addTypePropertyContext($context, $resourceClass, $resourceClass, $shortName); + + [$scopes, $iris, $typeProperties] = $this->getSubtypePropertyScopes($this->subtypeResolver, $this->propertyMetadataFactory, $resourceClass, array_keys($propertyNames), fn (string $class): array => iterator_to_array($this->propertyNameCollectionFactory->create($class, $propertyNameCollectionContext), false)); + $termOwners = []; + foreach ($scopes as $subtype => $properties) { + foreach ($properties as $propertyName => $scope) { + $scopeName = $this->subtypeResolver->getTypeName($scope); + $subtypeContext = []; + if (isset($typeProperties[$subtype][$propertyName])) { + $this->addTypePropertyContext($subtypeContext, $subtype, $scope, $scopeName); + } else { + $this->addPropertyContext($subtypeContext, $subtype, $propertyName, $scopeName, $propertyContext, $iris[$propertyName] ?? null); + } - if ($id = $propertyMetadata->getIris()) { - $id = 1 === (is_countable($id) ? \count($id) : 0) ? $id[0] : $id; - } + foreach ($subtypeContext as $term => $definition) { + if (isset($termOwners[$term]) && $context[$term] !== $definition) { + throw new RuntimeException(\sprintf('The subtypes "%s" and "%s" of the resource "%s" define the "%s" property differently in JSON-LD: declare the same "iris" and "jsonldContext" or rename one of the properties.', $termOwners[$term], $subtype, $resourceClass, $term)); + } - if (!$id) { - $id = \sprintf('%s/%s', $shortName, $convertedName); + $termOwners[$term] ??= $subtype; + $context[$term] = $definition; + } } + } - if (false === $propertyMetadata->isReadableLink()) { - $jsonldContext += [ - '@id' => $id, - '@type' => '@id', - ]; - } + return $context; + } - if (empty($jsonldContext)) { - $context[$convertedName] = $id; - } else { - $context[$convertedName] = $jsonldContext + [ - '@id' => $id, - ]; - } + private function addTypePropertyContext(array &$context, string $class, string $scope, string $scopeName): void + { + if (null === $typeProperty = $this->subtypeResolver?->getMapping($class)?->getTypeProperty()) { + return; } - return $context; + $convertedName = $this->nameConverter ? $this->nameConverter->normalize($typeProperty, $scope, self::FORMAT) : $typeProperty; + $context[$convertedName] ??= \sprintf('%s/%s', $scopeName, $convertedName); + } + + /** + * @param string|list|null $iris + */ + private function addPropertyContext(array &$context, string $resourceClass, string $propertyName, string $shortName, array $propertyContext, string|array|null $iris = null): void + { + $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $propertyContext); + + if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) { + return; + } + + $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName; + $jsonldContext = $propertyMetadata->getJsonldContext() ?? []; + + if ($id = $iris ?? $propertyMetadata->getIris()) { + $id = \is_array($id) && 1 === \count($id) ? $id[0] : $id; + } + + 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/ItemDenormalizer.php b/src/JsonLd/Serializer/ItemDenormalizer.php index c1f3d53acd0..23bd6eb3e1d 100644 --- a/src/JsonLd/Serializer/ItemDenormalizer.php +++ b/src/JsonLd/Serializer/ItemDenormalizer.php @@ -19,9 +19,11 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Serializer\AbstractItemNormalizer; use ApiPlatform\Serializer\OperationResourceClassResolverInterface; use ApiPlatform\Serializer\TagCollectorInterface; +use ApiPlatform\State\Exception\UnprocessableValueException; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; @@ -33,13 +35,15 @@ */ final class ItemDenormalizer extends AbstractItemNormalizer { - use ItemNormalizerTrait; + use ItemNormalizerTrait { + denormalize as private denormalizeItem; + } public const FORMAT = 'jsonld'; - public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null) + public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, ?SubtypeResolverInterface $subtypeResolver = null) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); } public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool @@ -52,6 +56,55 @@ public function supportsDenormalization(mixed $data, string $type, ?string $form return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context); } + public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed + { + $object = $this->denormalizeItem($data, $type, $format, $context); + + if (null !== $this->subtypeResolver && \is_array($data) && isset($data['@type']) && $this->resourceClassResolver->isResourceClass($type)) { + $resourceClass = $this->resourceClassResolver->getResourceClass(null, $type); + if ($object instanceof $resourceClass) { + $this->validateType((array) $data['@type'], $object, $resourceClass, $context); + } + } + + return $object; + } + + /** + * A "@type" naming a class of the discriminator maps the object is not an instance of contradicts its type property. + * + * @param array $types + */ + private function validateType(array $types, object $object, string $resourceClass, array $context): void + { + $classes = [$resourceClass, ...$this->subtypeResolver->getSubtypes($resourceClass)]; + $classesByName = []; + foreach ($classes as $class) { + foreach ($this->subtypeResolver->getTypes($class) as $typeName) { + $classesByName[$typeName][] = $class; + } + } + + foreach ($types as $typeName) { + if (!\is_string($typeName) || !isset($classesByName[$typeName]) || array_filter($classesByName[$typeName], static fn (string $class): bool => $object instanceof $class)) { + continue; + } + + // The map deciding between both classes is the one of their most specific common mapped parent + $namedClass = $classesByName[$typeName][0]; + $decidingClass = $resourceClass; + foreach ($classes as $class) { + if ($object instanceof $class && is_a($namedClass, $class, true) && is_a($class, $decidingClass, true) && null !== $this->subtypeResolver->getMapping($class)) { + $decidingClass = $class; + } + } + + $typeProperty = $this->subtypeResolver->getMapping($decidingClass)?->getTypeProperty() ?? '@type'; + + throw new UnprocessableValueException(\sprintf('The type "%s" does not match the "%s" property.', $typeName, $typeProperty), $typeName, isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$typeProperty : $typeProperty, UnprocessableValueException::TYPE_MISMATCH_ERROR); + } + } + public function getSupportedTypes(?string $format): array { return self::FORMAT === $format ? parent::getSupportedTypes($format) : []; diff --git a/src/JsonLd/Serializer/ItemNormalizer.php b/src/JsonLd/Serializer/ItemNormalizer.php index e63202613f6..63a484fe576 100644 --- a/src/JsonLd/Serializer/ItemNormalizer.php +++ b/src/JsonLd/Serializer/ItemNormalizer.php @@ -23,6 +23,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Serializer\AbstractItemNormalizer; @@ -50,9 +51,9 @@ final class ItemNormalizer extends AbstractItemNormalizer public const FORMAT = 'jsonld'; - public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, private ?OperationMetadataFactoryInterface $operationMetadataFactory = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null) + public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, private ?OperationMetadataFactoryInterface $operationMetadataFactory = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, ?SubtypeResolverInterface $subtypeResolver = null) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); } /** @@ -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; @@ -156,6 +157,13 @@ private function resolveType(string $resourceClass, bool $isResourceClass, array return null; } + // A subtype is typed by its most specific class, documented as a subclass of the resource (and of its types) + if ($isResourceClass && null !== $this->subtypeResolver && null !== $discriminatedClass = $this->getDiscriminatedClass($data, $resourceClass)) { + $subtypeTypes = $this->subtypeResolver->getTypes($discriminatedClass); + + return 1 === \count($subtypeTypes) ? $subtypeTypes[0] : $subtypeTypes; + } + $types = $operation instanceof HttpOperation ? $operation->getTypes() : null; if (null === $types) { $typeClass = $isResourceClass ? $resourceClass : ($operation->getClass() ?? $resourceClass); diff --git a/src/JsonLd/SubtypePropertyScopeTrait.php b/src/JsonLd/SubtypePropertyScopeTrait.php new file mode 100644 index 00000000000..0af4cbea727 --- /dev/null +++ b/src/JsonLd/SubtypePropertyScopeTrait.php @@ -0,0 +1,108 @@ + + * + * 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\JsonLd; + +use ApiPlatform\Metadata\Exception\RuntimeException; +use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; + +/** + * Scopes the properties the subtypes of a resource declare, shared by the JSON-LD context and the Hydra documentation. + * + * A property is declared by a subtype when no mapped parent declares it. Declared by several subtypes, it is one + * property scoped to their closest common mapped parent. The type property of a map is declared by the class of the map. + * + * @internal + */ +trait SubtypePropertyScopeTrait +{ + /** + * @param list $resourcePropertyNames + * @param callable(class-string): list $propertyNames + * + * @return array{array>, array>, array>} the scope of each property declared by a subtype, the explicit IRIs of these properties, the type properties + */ + private function getSubtypePropertyScopes(SubtypeResolverInterface $subtypeResolver, PropertyMetadataFactoryInterface $propertyMetadataFactory, string $resourceClass, array $resourcePropertyNames, callable $propertyNames): array + { + $declared = [$resourceClass => array_fill_keys($resourcePropertyNames, true)]; + if (null !== $resourceTypeProperty = $subtypeResolver->getMapping($resourceClass)?->getTypeProperty()) { + $declared[$resourceClass][$resourceTypeProperty] = true; + } + + $typeProperties = []; + $declarers = []; + foreach ($subtypeResolver->getSubtypes($resourceClass) as $subtype) { + $declared[$subtype] = array_fill_keys($propertyNames($subtype), true); + if (null !== ($typeProperty = $subtypeResolver->getMapping($subtype)?->getTypeProperty()) && !isset($declared[$subtype][$typeProperty])) { + $declared[$subtype][$typeProperty] = $typeProperties[$subtype][$typeProperty] = true; + } + + foreach ($declared[$subtype] as $propertyName => $_) { + foreach ($declared as $class => $classPropertyNames) { + if ($class !== $subtype && isset($classPropertyNames[$propertyName]) && is_a($subtype, $class, true)) { + continue 2; + } + } + + $declarers[$propertyName][] = $subtype; + } + } + + $scopes = []; + $iris = []; + foreach ($declarers as $propertyName => $subtypes) { + $scope = $subtypes[0]; + if (\count($subtypes) > 1) { + $scope = $resourceClass; + foreach (array_keys($declared) as $class) { + if (is_a($class, $scope, true) && $this->isParentOfAll($class, $subtypes)) { + $scope = $class; + } + } + } + + $irisOwner = null; + foreach ($subtypes as $subtype) { + $scopes[$subtype][$propertyName] = $scope; + if (isset($typeProperties[$subtype][$propertyName]) || !$propertyIris = $propertyMetadataFactory->create($subtype, $propertyName)->getIris()) { + continue; + } + + $propertyIris = 1 === \count($propertyIris) ? $propertyIris[0] : $propertyIris; + if (null !== $irisOwner && $iris[$propertyName] !== $propertyIris) { + throw new RuntimeException(\sprintf('The subtypes "%s" and "%s" of the resource "%s" give the "%s" property different "iris": declare the same ones or rename one of the properties.', $irisOwner, $subtype, $resourceClass, $propertyName)); + } + + $irisOwner ??= $subtype; + $iris[$propertyName] = $propertyIris; + } + } + + return [$scopes, $iris, $typeProperties]; + } + + /** + * @param list $classes + */ + private function isParentOfAll(string $parent, array $classes): bool + { + foreach ($classes as $class) { + if (!is_a($class, $parent, true)) { + return false; + } + } + + return true; + } +} diff --git a/src/JsonLd/composer.json b/src/JsonLd/composer.json index 7829d16d3ed..53abd719bdb 100644 --- a/src/JsonLd/composer.json +++ b/src/JsonLd/composer.json @@ -24,9 +24,9 @@ ], "require": { "php": ">=8.2", - "api-platform/state": "^5.0", - "api-platform/metadata": "^5.0", - "api-platform/serializer": "^5.0" + "api-platform/state": "^5.1", + "api-platform/metadata": "^5.1", + "api-platform/serializer": "^5.1" }, "autoload": { "psr-4": { diff --git a/src/JsonSchema/SchemaFactory.php b/src/JsonSchema/SchemaFactory.php index 042c72dc1de..89c8d89586a 100644 --- a/src/JsonSchema/SchemaFactory.php +++ b/src/JsonSchema/SchemaFactory.php @@ -23,6 +23,8 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\Util\TypeHelper; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\TypeInfo\Type; @@ -50,8 +52,9 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI // Edge case where the related resource is not readable (for example: NotExposed) but we have groups to read the whole related object public const OPENAPI_DEFINITION_NAME = 'openapi_definition_name'; public const PARTIAL_UPDATE = 'partial_update'; + private const DISCRIMINATOR_UPDATE = 'discriminator_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, private readonly bool $resourcePolymorphism = false) { if (!$definitionNameFactory) { $this->definitionNameFactory = new DefinitionNameFactory(); @@ -82,6 +85,9 @@ public function buildSchema(string $className, string $format = 'json', string $ } } + $discriminatorUpdate = $serializerContext[self::DISCRIMINATOR_UPDATE] ?? null; + unset($serializerContext[self::DISCRIMINATOR_UPDATE]); + if (null === $inputOrOutputClass) { // input or output disabled return $schema; @@ -100,8 +106,8 @@ public function buildSchema(string $className, string $format = 'json', string $ return $schema; } - $isJsonMergePatch = 'json' === $format && 'PATCH' === $method && Schema::TYPE_INPUT === $type; - $isNonStandardPut = Schema::TYPE_INPUT === $type && 'PUT' === $method && !($operation?->getExtraProperties()['standard_put'] ?? true); + $isJsonMergePatch = 'merge-patch' === $discriminatorUpdate || ('json' === $format && 'PATCH' === $method && Schema::TYPE_INPUT === $type); + $isNonStandardPut = 'partial' === $discriminatorUpdate || (Schema::TYPE_INPUT === $type && 'PUT' === $method && !($operation?->getExtraProperties()['standard_put'] ?? true)); $isPartialUpdate = $isJsonMergePatch || $isNonStandardPut; $definitionFormat = match (true) { default => $format, @@ -129,6 +135,21 @@ public function buildSchema(string $className, string $format = 'json', string $ return $schema; } + $mapping = Schema::VERSION_SWAGGER !== $version && ($this->resourcePolymorphism || !$this->resourceClassResolver?->isResourceClass($inputOrOutputClass)) ? $this->classDiscriminatorResolver?->getMappingForClass($inputOrOutputClass) : null; + $subtypes = $mapping ? $this->getDirectSubtypes($mapping, $inputOrOutputClass) : []; + $hasOwnBranch = $subtypes && [] !== array_keys($mapping->getTypesMapping(), $inputOrOutputClass, true); + $subtypeContext = $serializerContext + [self::FORCE_SUBSCHEMA => true, self::DISCRIMINATOR_UPDATE => match (true) { + $isJsonMergePatch => 'merge-patch', + $isPartialUpdate => 'partial', + default => null, + }]; + + if ($subtypes && !$hasOwnBranch) { + $this->buildDiscriminatorDefinition($schema, $definitionName, $inputOrOutputClass, $mapping, $subtypes, false, $format, $type, $subtypeContext, $serializerContext); + + return $schema; + } + /** @var \ArrayObject $definition */ $definition = new \ArrayObject(['type' => 'object']); $definitions[$definitionName] = $definition; @@ -172,9 +193,126 @@ public function buildSchema(string $className, string $format = 'json', string $ $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type); } + if ($this->resourcePolymorphism || !$this->resourceClassResolver?->isResourceClass($inputOrOutputClass)) { + $this->addDiscriminatorProperties($definition, $inputOrOutputClass, $format, $serializerContext, $isPartialUpdate); + } + + if ($hasOwnBranch) { + $this->buildDiscriminatorDefinition($schema, $definitionName, $inputOrOutputClass, $mapping, $subtypes, true, $format, $type, $subtypeContext, $serializerContext); + } + return $schema; } + /** + * @param array $subtypes + */ + private function buildDiscriminatorDefinition(Schema $schema, string $definitionName, string $class, ClassDiscriminatorMapping $mapping, array $subtypes, bool $hasOwnBranch, string $format, string $type, array $subtypeContext, array $serializerContext): void + { + $version = $schema->getVersion(); + $prefix = $this->getSchemaUriPrefix($version); + $definitions = $schema->getDefinitions(); + /** @var \ArrayObject $definition */ + $definition = $definitions[$definitionName] ?? new \ArrayObject(); + + $oneOf = $refs = []; + if ($hasOwnBranch) { + $ownKeywords = array_flip(['type', 'properties', 'required', 'additionalProperties']); + $oneOf[] = array_intersect_key($definition->getArrayCopy(), $ownKeywords); + $definition->exchangeArray(array_diff_key($definition->getArrayCopy(), $ownKeywords)); + foreach (array_keys($mapping->getTypesMapping(), $class, true) as $typeValue) { + $refs[(string) $typeValue] = $prefix.$definitionName; + } + } else { + $definition->exchangeArray([]); + } + + // registered before recursing so that a subclass referencing its parent does not loop + $definitions[$definitionName] = $definition; + + $branches = []; + foreach ($subtypes as $typeValue => $subtype) { + $subSchema = new Schema($version); + $subSchema->setDefinitions($definitions); + $result = ($this->schemaFactory ?: $this)->buildSchema($subtype, $format, $type, null, $subSchema, $subtypeContext); + + if (isset($result['$ref'])) { + $branches[$result['$ref']] = ['$ref' => $result['$ref']]; + $refs[$typeValue] = $result['$ref']; + } + } + + $definition['oneOf'] = [...$oneOf, ...array_values($branches)]; + if (Schema::VERSION_OPENAPI === $version) { + $definition['discriminator'] = ['propertyName' => $this->normalizeTypeProperty($mapping->getTypeProperty(), $class, $format, $serializerContext), 'mapping' => $refs]; + } + } + + /** + * @return array the strict subclasses declared in the map, indexed by type value + */ + private 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; + } + + /** + * @param \ArrayObject $definition + */ + private function addDiscriminatorProperties(\ArrayObject $definition, string $class, string $format, array $serializerContext, bool $isPartialUpdate): void + { + foreach ($this->getDiscriminatorTypes($class) as $typeProperty => ['values' => $values, 'required' => $required]) { + $name = $this->normalizeTypeProperty($typeProperty, $class, $format, $serializerContext); + $definition['properties'][$name] = ['type' => 'string', 'enum' => $values]; + if ($required && !$isPartialUpdate && !\in_array($name, $definition['required'] ?? [], true)) { + $definition['required'][] = $name; + } + } + } + + /** + * The type properties of every discriminator map the class is declared in, from the nearest map to the outer ones. + * + * @return array, required: bool}> + */ + private function getDiscriminatorTypes(string $class): array + { + $types = []; + $mapped = $from = $class; + while ($this->classDiscriminatorResolver && null !== $from && $mapping = $this->classDiscriminatorResolver->getMappingForMappedObject($from)) { + $declaring = $from; + while (false !== $declaring && $this->classDiscriminatorResolver->getMappingForClass($declaring) !== $mapping) { + $declaring = get_parent_class($declaring); + } + + $values = array_map(strval(...), array_keys($mapping->getTypesMapping(), $mapped, true)); + if (!$values && null !== $value = $mapping->getMappedObjectType($mapped)) { + $values = [$value]; + } + + if ($values) { + $types[$mapping->getTypeProperty()] ??= ['values' => $values, 'required' => null === $mapping->getDefaultType() || !array_intersect($values, [$mapping->getDefaultType()])]; + } + + $mapped = $declaring; + $from = false === $declaring ? null : (get_parent_class($declaring) ?: null); + } + + return $types; + } + + private function normalizeTypeProperty(string $typeProperty, string $class, string $format, array $serializerContext): string + { + return $this->nameConverter ? $this->nameConverter->normalize($typeProperty, $class, $format, $serializerContext) : $typeProperty; + } + private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void { $version = $schema->getVersion(); 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/DiscriminatedBike.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedBike.php new file mode 100644 index 00000000000..36dd46647c4 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedBike.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\JsonSchema\Tests\Fixtures\Discriminator; + +final class DiscriminatedBike extends DiscriminatedVehicle +{ +} diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCar.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCar.php new file mode 100644 index 00000000000..5470eb6e514 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCar.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\JsonSchema\Tests\Fixtures\Discriminator; + +final class DiscriminatedCar extends DiscriminatedVehicle +{ +} 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/Fixtures/Discriminator/DiscriminatedVehicle.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedVehicle.php new file mode 100644 index 00000000000..14c6c8b22d6 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedVehicle.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: 'vehicleType', mapping: ['car' => DiscriminatedCar::class, 'bike' => DiscriminatedBike::class], defaultType: 'car')] +abstract class DiscriminatedVehicle +{ + public int $wheels = 0; +} diff --git a/src/JsonSchema/Tests/SchemaFactoryTest.php b/src/JsonSchema/Tests/SchemaFactoryTest.php index 56093795b2c..d4221d2c97e 100644 --- a/src/JsonSchema/Tests/SchemaFactoryTest.php +++ b/src/JsonSchema/Tests/SchemaFactoryTest.php @@ -19,6 +19,14 @@ 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\DiscriminatedBike; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedCar; +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\Discriminator\DiscriminatedVehicle; use ApiPlatform\JsonSchema\Tests\Fixtures\DummyResourceInterface; use ApiPlatform\JsonSchema\Tests\Fixtures\Enum\GenderTypeEnum; use ApiPlatform\JsonSchema\Tests\Fixtures\GenericChild; @@ -42,6 +50,11 @@ 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\NameConverter\CamelCaseToSnakeCaseNameConverter; +use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\TypeInfo\Type; @@ -484,6 +497,139 @@ 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/DiscriminatedCat'], + ['$ref' => '#/components/schemas/DiscriminatedDog'], + ], $base['oneOf']); + $this->assertSame([ + 'propertyName' => 'species', + 'mapping' => [ + 'cat' => '#/components/schemas/DiscriminatedCat', + 'dog' => '#/components/schemas/DiscriminatedDog', + ], + ], $base['discriminator']); + + $cat = $definitions['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['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/DiscriminatedCat'], + ['$ref' => '#/definitions/DiscriminatedDog'], + ], $definitions['DiscriminatedAnimal']['oneOf']); + $this->assertArrayNotHasKey('discriminator', $definitions['DiscriminatedAnimal']); + $this->assertSame(['type' => 'string', 'enum' => ['cat']], $definitions['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', + 'additionalProperties' => false, + 'properties' => [ + 'name' => ['type' => 'string'], + 'kind' => ['type' => 'string', 'enum' => ['gadget']], + ], + 'required' => ['kind'], + ], json_decode(json_encode($base['oneOf'][0]), true)); + $this->assertSame(['$ref' => '#/components/schemas/DiscriminatedPhone'], $base['oneOf'][1]); + $this->assertSame('#/components/schemas/'.$rootDefinitionKey, $base['discriminator']['mapping']['gadget']); + + $phone = $definitions['DiscriminatedPhone']; + $this->assertSame(['type' => 'string', 'enum' => ['phone']], $phone['properties']['kind']); + $this->assertFalse($phone['additionalProperties']); + } + + public function testBuildSchemaDoesNotRequireTheTypePropertyOfTheDefaultType(): void + { + $definitions = $this->createDiscriminatorSchemaFactory()->buildSchema(DiscriminatedVehicle::class, 'json', Schema::TYPE_INPUT)->getDefinitions(); + + $this->assertSame(['type' => 'string', 'enum' => ['car']], $definitions['DiscriminatedCar']['properties']['vehicleType']); + $this->assertArrayHasKey('wheels', $definitions['DiscriminatedCar']['properties']); + $this->assertNotContains('vehicleType', $definitions['DiscriminatedCar']['required'] ?? []); + $this->assertContains('vehicleType', $definitions['DiscriminatedBike']['required']); + } + + public function testBuildSchemaNormalizesTheTypePropertyName(): void + { + $schema = $this->createDiscriminatorSchemaFactory(nameConverter: new CamelCaseToSnakeCaseNameConverter())->buildSchema(DiscriminatedVehicle::class, 'json', Schema::TYPE_INPUT, null, new Schema(Schema::VERSION_OPENAPI)); + $definitions = $schema->getDefinitions(); + + $this->assertSame('vehicle_type', $definitions['DiscriminatedVehicle']['discriminator']['propertyName']); + $this->assertArrayHasKey('vehicle_type', $definitions['DiscriminatedBike']['properties']); + $this->assertContains('vehicle_type', $definitions['DiscriminatedBike']['required']); + } + + 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, ?NameConverterInterface $nameConverter = null): SchemaFactory + { + $propertyNames = [ + DiscriminatedAnimal::class => ['name'], + DiscriminatedCat::class => ['lives', 'name'], + DiscriminatedDog::class => ['goodBoy', 'name'], + DiscriminatedGadget::class => ['name'], + DiscriminatedPhone::class => ['name', 'number'], + DiscriminatedVehicle::class => ['wheels'], + DiscriminatedCar::class => ['wheels'], + DiscriminatedBike::class => ['wheels'], + ]; + $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'], 'wheels' => [Type::int(), 'integer']]; + $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, + nameConverter: $nameConverter, + 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/JsonSchema/composer.json b/src/JsonSchema/composer.json index a2ccfa6da61..f85d5d748a7 100644 --- a/src/JsonSchema/composer.json +++ b/src/JsonSchema/composer.json @@ -25,7 +25,7 @@ ], "require": { "php": ">=8.2", - "api-platform/metadata": "^5.0", + "api-platform/metadata": "^5.1", "symfony/console": "^7.4 || ^8.0", "symfony/property-info": "^7.4 || ^8.0", "symfony/serializer": "^7.4 || ^8.0", diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 0aa864d60df..0c95752d729 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -151,6 +151,8 @@ use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolver; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolver; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\Inflector; use ApiPlatform\OpenApi\Command\OpenApiCommand; @@ -169,6 +171,7 @@ use ApiPlatform\State\CallableProvider; use ApiPlatform\State\DenormalizationViolationFactoryInterface; use ApiPlatform\State\ErrorProvider; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; use ApiPlatform\State\Pagination\Pagination; use ApiPlatform\State\Pagination\PaginationOptions; use ApiPlatform\State\ParameterProviderInterface; @@ -217,6 +220,7 @@ 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\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; @@ -312,6 +316,14 @@ public function register(): void ); }); + $this->app->singleton(SubtypeResolverInterface::class, static function (Application $app) { + return new SubtypeResolver( + new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), + $app->make(ResourceNameCollectionFactoryInterface::class), + $app->make(ResourceMetadataCollectionFactoryInterface::class), + ); + }); + $this->app->singleton(SerializerClassMetadataFactory::class, static function (Application $app) { return new SerializerClassMetadataFactory($app->make(ClassMetadataFactoryInterface::class)); }); @@ -440,7 +452,8 @@ public function register(): void $this->app->extend(ResourceMetadataCollectionFactoryInterface::class, static function (ResourceMetadataCollectionFactoryInterface $inner, Application $app) { return new ObjectMapperMetadataCollectionFactory( $inner, - $app->make(ObjectMapperMetadataFactoryInterface::class) + $app->make(ObjectMapperMetadataFactoryInterface::class), + static fn (): ?SubtypeResolverInterface => self::getSubtypeResolver($app) ); }); } @@ -450,6 +463,14 @@ public function register(): void return new Metadata\Resource\Factory\ParameterResourceMetadataCollectionFactory($inner, $app->make(ModelMetadata::class), new \Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter()); }); + $this->app->extend(ResourceMetadataCollectionFactoryInterface::class, static function (ResourceMetadataCollectionFactoryInterface $inner, Application $app) { + if (!$app['config']->get('api-platform.serializer.discriminator_map', false)) { + return $inner; + } + + return new Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory(new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), $inner, $app['config']->get('api-platform.defaults', [])); + }); + $this->app->singleton(OperationMetadataFactory::class, static function (Application $app) { return new OperationMetadataFactory($app->make(ResourceNameCollectionFactoryInterface::class), $app->make(ResourceMetadataCollectionFactoryInterface::class)); }); @@ -527,9 +548,15 @@ public function register(): void $this->app->singleton(ObjectMapperMetadataFactoryInterface::class, ReflectionObjectMapperMetadataFactory::class); $this->app->singleton(ObjectMapper::class, static function (Application $app) { - return new ObjectMapper( + $objectMapper = new ObjectMapper( $app->make(ObjectMapperMetadataFactoryInterface::class) ); + + if (!$subtypeResolver = self::getSubtypeResolver($app)) { + return $objectMapper; + } + + return new SubtypeObjectMapper($objectMapper, $subtypeResolver, $app->make(ObjectMapperMetadataFactoryInterface::class)); }); $this->app->extend(ProviderInterface::class, static function (ProviderInterface $inner, Application $app) { @@ -713,7 +740,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(IriConverterInterface::class), $app->make(NameConverterInterface::class), - $defaultContext + $defaultContext, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -745,6 +773,7 @@ public function register(): void // $app->make(TagCollectorInterface::class) null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -767,6 +796,7 @@ public function register(): void $defaultContext, null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -815,6 +845,7 @@ public function register(): void $app->make(ResourceMetadataCollectionFactoryInterface::class), $app->make(ResourceAccessCheckerInterface::class), // $app->make(TagCollectorInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -970,6 +1001,8 @@ public function register(): void $app->make(NameConverterInterface::class), $app->make(ResourceClassResolverInterface::class), $app->make(DefinitionNameFactoryInterface::class), + new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), + null !== self::getSubtypeResolver($app), ); }); $this->app->singleton(JsonApiSchemaFactory::class, static function (Application $app) { @@ -980,6 +1013,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), + subtypeResolver: self::getSubtypeResolver($app), ); }); $this->app->singleton(HydraSchemaFactory::class, static function (Application $app) { @@ -1013,7 +1047,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(NameConverterInterface::class), $defaultContext, - $entrypointEnabled + $entrypointEnabled, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1108,6 +1143,7 @@ public function register(): void operationResourceResolver: $app->make(OperationResourceClassResolverInterface::class), identifiersExtractor: $app->make(IdentifiersExtractorInterface::class), useIriAsId: $useIriAsId, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1127,6 +1163,7 @@ public function register(): void $defaultContext, $app->make(ResourceMetadataCollectionFactoryInterface::class), $app->make(ResourceAccessCheckerInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1230,6 +1267,7 @@ public function register(): void null, null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1250,6 +1288,7 @@ public function register(): void $app->make(ResourceAccessCheckerInterface::class), null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1690,4 +1729,9 @@ public function boot(): void $this->loadRoutesFrom(__DIR__.'/routes/api.php'); } + + private static function getSubtypeResolver(Application $app): ?SubtypeResolverInterface + { + return $app['config']->get('api-platform.serializer.discriminator_map', false) ? $app->make(SubtypeResolverInterface::class) : null; + } } diff --git a/src/Laravel/State/DenormalizationViolationFactory.php b/src/Laravel/State/DenormalizationViolationFactory.php index c09c821a70a..d632e617500 100644 --- a/src/Laravel/State/DenormalizationViolationFactory.php +++ b/src/Laravel/State/DenormalizationViolationFactory.php @@ -16,6 +16,7 @@ use ApiPlatform\Laravel\ApiResource\ValidationError; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\DenormalizationViolationFactoryInterface; +use ApiPlatform\State\Exception\UnprocessableValueException; use Illuminate\Contracts\Validation\Rule as LaravelRule; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; @@ -96,6 +97,10 @@ public function handle(NotNormalizableValueException|PartialDenormalizationExcep */ private function buildViolation(NotNormalizableValueException $exception, Operation $operation): ?array { + if ($exception instanceof UnprocessableValueException) { + return $this->violation((string) $exception->getPath(), $exception->getMessage(), $exception->getViolationCode()); + } + $rules = $operation->getRules(); if (\is_callable($rules)) { $rules = $rules(); diff --git a/src/Laravel/composer.json b/src/Laravel/composer.json index 6fcac570285..4139cb83c3d 100644 --- a/src/Laravel/composer.json +++ b/src/Laravel/composer.json @@ -29,15 +29,15 @@ "require": { "php": ">=8.2", "api-platform/documentation": "^5.0", - "api-platform/hal": "^5.0", - "api-platform/hydra": "^5.0", - "api-platform/json-api": "^5.0", - "api-platform/json-schema": "^5.0", - "api-platform/jsonld": "^5.0", - "api-platform/metadata": "^5.0", + "api-platform/hal": "^5.1", + "api-platform/hydra": "^5.1", + "api-platform/json-api": "^5.1", + "api-platform/json-schema": "^5.1", + "api-platform/jsonld": "^5.1", + "api-platform/metadata": "^5.1", "api-platform/openapi": "^5.0", - "api-platform/serializer": "^5.0", - "api-platform/state": "^5.0", + "api-platform/serializer": "^5.1", + "api-platform/state": "^5.1", "illuminate/config": "^11.0 || ^12.0 || ^13.0", "illuminate/container": "^11.0 || ^12.0 || ^13.0", "illuminate/contracts": "^11.0 || ^12.0 || ^13.0", 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/Resource/Factory/ObjectMapperMetadataCollectionFactory.php b/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php index 37204def6a4..8ae8eafd1a5 100644 --- a/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php +++ b/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php @@ -16,14 +16,19 @@ use ApiPlatform\Doctrine\Odm\State\Options as OdmOptions; use ApiPlatform\Doctrine\Orm\State\Options; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\SubtypeResolverInterface; use Symfony\Component\ObjectMapper\Metadata\Mapping; use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; class ObjectMapperMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface { + /** + * @param SubtypeResolverInterface|\Closure(): ?SubtypeResolverInterface|null $subtypeResolver + */ public function __construct( private readonly ResourceMetadataCollectionFactoryInterface $decorated, private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + private SubtypeResolverInterface|\Closure|null $subtypeResolver = null, ) { } @@ -93,7 +98,11 @@ private function canBeMapped(string $class): bool|array { try { $r = new \ReflectionClass($class); - if (!$r->isInstantiable() || !($mapping = $this->objectMapperMetadata->create($r->newInstanceWithoutConstructor(), null, ['_api_check_can_be_mapped' => true]))) { + if (!$r->isInstantiable()) { + return $this->canSubtypesBeMapped($class); + } + + if (!($mapping = $this->objectMapperMetadata->create($r->newInstanceWithoutConstructor(), null, ['_api_check_can_be_mapped' => true]))) { return false; } } catch (\ReflectionException $e) { @@ -102,4 +111,24 @@ private function canBeMapped(string $class): bool|array return $mapping; } + + /** + * @return bool|list + */ + private function canSubtypesBeMapped(string $class): bool|array + { + if ($this->subtypeResolver instanceof \Closure) { + $this->subtypeResolver = ($this->subtypeResolver)(); + } + + $mappings = []; + foreach ($this->subtypeResolver?->getSubtypes($class) ?? [] as $subtype) { + $subtypeMapping = $this->canBeMapped($subtype); + if (\is_array($subtypeMapping)) { + array_push($mappings, ...$subtypeMapping); + } + } + + return $mappings ?: false; + } } diff --git a/src/Metadata/Resource/Factory/OperationDefaultsTrait.php b/src/Metadata/Resource/Factory/OperationDefaultsTrait.php index e53afe0b931..158c329ddba 100644 --- a/src/Metadata/Resource/Factory/OperationDefaultsTrait.php +++ b/src/Metadata/Resource/Factory/OperationDefaultsTrait.php @@ -149,12 +149,12 @@ private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource $graphQlOperations = []; foreach ($operations as $operation) { [$key, $operation] = $this->getOperationWithDefaults($resource, $operation); - $graphQlOperations[$key] = $operation; + $graphQlOperations[$key] = $operation->withExtraProperties($operation->getExtraProperties() + ['graphql_default_operation' => true]); } if ($resource->getMercure()) { [$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}.")); - $graphQlOperations[$key] = $operation; + $graphQlOperations[$key] = $operation->withExtraProperties($operation->getExtraProperties() + ['graphql_default_operation' => true]); } return $resource->withGraphQlOperations($graphQlOperations); diff --git a/src/Metadata/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactory.php b/src/Metadata/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactory.php new file mode 100644 index 00000000000..2e2f0f88379 --- /dev/null +++ b/src/Metadata/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactory.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\Metadata\Resource\Factory; + +use ApiPlatform\Metadata\Exception\RuntimeException; +use ApiPlatform\Metadata\GraphQl\Query; +use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\Util\CamelCaseToSnakeCaseNameConverter; +use Psr\Log\NullLogger; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; + +/** + * GraphQL does not support resources with a discriminator map yet: the operations + * added by default are dropped, explicitly declared ones are rejected. + */ +final class PolymorphicGraphQlResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface +{ + use OperationDefaultsTrait; + + public function __construct( + private readonly ClassDiscriminatorResolverInterface $classDiscriminatorResolver, + private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null, + array $defaults = [], + ) { + $this->defaults = $defaults; + $this->logger = new NullLogger(); + $this->camelCaseToSnakeCaseNameConverter = new CamelCaseToSnakeCaseNameConverter(); + } + + public function create(string $resourceClass): ResourceMetadataCollection + { + $resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass); + + if (!$resourceMetadataCollection->count() || !$this->isPolymorphic($resourceClass)) { + return $resourceMetadataCollection; + } + + foreach ($resourceMetadataCollection as $key => $resource) { + $graphQlOperations = []; + $hadDefaults = false; + foreach ($resource->getGraphQlOperations() ?? [] as $name => $operation) { + if ($operation->getExtraProperties()['graphql_default_operation'] ?? false) { + $hadDefaults = true; + continue; + } + + if ($operation instanceof Query && $operation->getNested()) { + $graphQlOperations[$name] = $operation; + continue; + } + + throw new RuntimeException(\sprintf('GraphQL is not supported yet for "%s", a resource with a discriminator map. Remove its "graphQlOperations" or set them to an empty array.', $resourceClass)); + } + + if ($hadDefaults) { + $completed = $this->completeGraphQlOperations($resource->withGraphQlOperations($graphQlOperations))->getGraphQlOperations(); + foreach ($completed as $name => $operation) { + if (!isset($graphQlOperations[$name])) { + [$name, $operation] = $this->getOperationWithDefaults($resource, $operation); + } + $graphQlOperations[$name] = $operation; + } + } + + if ($resource->getGraphQlOperations() !== $graphQlOperations) { + $resourceMetadataCollection[$key] = $resource->withGraphQlOperations($graphQlOperations); + } + } + + return $resourceMetadataCollection; + } + + private function isPolymorphic(string $resourceClass): bool + { + if (null !== $this->classDiscriminatorResolver->getMappingForClass($resourceClass)) { + return true; + } + + foreach (class_parents($resourceClass) ?: [] as $parent) { + if (\in_array($resourceClass, $this->classDiscriminatorResolver->getMappingForClass($parent)?->getTypesMapping() ?? [], true)) { + return true; + } + } + + return false; + } +} diff --git a/src/Metadata/SubtypeResolver.php b/src/Metadata/SubtypeResolver.php new file mode 100644 index 00000000000..dd445b9f1bb --- /dev/null +++ b/src/Metadata/SubtypeResolver.php @@ -0,0 +1,107 @@ + + * + * 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; + +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; + +final class SubtypeResolver implements SubtypeResolverInterface +{ + /** @var array> */ + private array $subtypesCache = []; + /** @var array|null */ + private ?array $resourceClasses = null; + + public function __construct( + private readonly ClassDiscriminatorResolverInterface $classDiscriminatorResolver, + private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, + private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, + ) { + } + + public function getMapping(string $class): ?ClassDiscriminatorMapping + { + return $this->classDiscriminatorResolver->getMappingForClass($class); + } + + public function getDirectSubtypes(string $class): array + { + $subtypes = []; + foreach ($this->getMapping($class)?->getTypesMapping() ?? [] as $typeValue => $typeClass) { + if ($typeClass !== $class && is_a($typeClass, $class, true)) { + $subtypes[(string) $typeValue] = $typeClass; + } + } + + return $subtypes; + } + + public function getSubtypes(string $class): array + { + if (isset($this->subtypesCache[$class])) { + return $this->subtypesCache[$class]; + } + + $subtypes = []; + foreach ($this->getDirectSubtypes($class) as $subtype) { + $subtypes[$subtype] = $subtype; + foreach ($this->getSubtypes($subtype) as $nestedSubtype) { + $subtypes[$nestedSubtype] = $nestedSubtype; + } + } + + return $this->subtypesCache[$class] = array_values($subtypes); + } + + public function getTypeName(string $class): string + { + return $this->getResource($class)?->getShortName() ?? $this->getClassShortName($class); + } + + public function getTypes(string $class): array + { + if (null === $resource = $this->getResource($class)) { + return [$this->getClassShortName($class)]; + } + + return $resource->getTypes() ?? [(string) $resource->getShortName()]; + } + + private function getResource(string $class): ?ApiResource + { + if (null === $this->resourceClasses) { + $this->resourceClasses = []; + foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) { + $this->resourceClasses[$resourceClass] = true; + } + } + + if (!isset($this->resourceClasses[$class])) { + return null; + } + + foreach ($this->resourceMetadataCollectionFactory->create($class) as $resource) { + return $resource; + } + + return null; + } + + private function getClassShortName(string $class): string + { + return false === ($position = strrpos($class, '\\')) ? $class : substr($class, $position + 1); + } +} diff --git a/src/Metadata/SubtypeResolverInterface.php b/src/Metadata/SubtypeResolverInterface.php new file mode 100644 index 00000000000..328e627dccc --- /dev/null +++ b/src/Metadata/SubtypeResolverInterface.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\Metadata; + +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; + +/** + * Resolves the subtypes a resource exposes through serializer discriminator maps (resource polymorphism). + * + * Only strict subclasses declared in a map are subtypes. + */ +interface SubtypeResolverInterface +{ + public function getMapping(string $class): ?ClassDiscriminatorMapping; + + /** + * @return array the subtypes declared in the map of the class, indexed by type value + */ + public function getDirectSubtypes(string $class): array; + + /** + * @return list the subtypes declared in the map of the class and, recursively, in the maps of its subtypes + */ + public function getSubtypes(string $class): array; + + /** + * Returns the name of a class in JSON-LD and Hydra: the short name of its resource, or of the class. + */ + public function getTypeName(string $class): string; + + /** + * Returns the JSON-LD types of a class: the types of its resource, or the short name of the class. + * + * @return list + */ + public function getTypes(string $class): array; +} diff --git a/src/Metadata/Tests/Resource/Factory/AttributesResourceMetadataCollectionFactoryTest.php b/src/Metadata/Tests/Resource/Factory/AttributesResourceMetadataCollectionFactoryTest.php index c0975b9f462..86bba282a80 100644 --- a/src/Metadata/Tests/Resource/Factory/AttributesResourceMetadataCollectionFactoryTest.php +++ b/src/Metadata/Tests/Resource/Factory/AttributesResourceMetadataCollectionFactoryTest.php @@ -62,11 +62,11 @@ class AttributesResourceMetadataCollectionFactoryTest extends TestCase private function getDefaultGraphqlOperations(string $shortName, string $class, mixed $provider = null): array { return [ - 'collection_query' => new QueryCollection(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider), - 'item_query' => new Query(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider), - 'update' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'update', description: "Updates a $shortName.", provider: $provider), - 'delete' => new DeleteMutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'delete', description: "Deletes a $shortName.", provider: $provider), - 'create' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'create', description: "Creates a $shortName.", provider: $provider), + 'collection_query' => new QueryCollection(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider, extraProperties: ['graphql_default_operation' => true]), + 'item_query' => new Query(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider, extraProperties: ['graphql_default_operation' => true]), + 'update' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'update', description: "Updates a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]), + 'delete' => new DeleteMutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'delete', description: "Deletes a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]), + 'create' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'create', description: "Creates a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]), ]; } diff --git a/src/Metadata/Tests/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactoryTest.php b/src/Metadata/Tests/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactoryTest.php new file mode 100644 index 00000000000..2db9d7a8106 --- /dev/null +++ b/src/Metadata/Tests/Resource/Factory/PolymorphicGraphQlResourceMetadataCollectionFactoryTest.php @@ -0,0 +1,111 @@ + + * + * 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\Resource\Factory; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Exception\RuntimeException; +use ApiPlatform\Metadata\GraphQl\Query; +use ApiPlatform\Metadata\GraphQl\QueryCollection; +use ApiPlatform\Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory; +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; + +final class PolymorphicGraphQlResourceMetadataCollectionFactoryTest extends TestCase +{ + public function testDefaultOperationsAreReplacedByNestedOnes(): void + { + $factory = $this->createFactory([ + 'item_query' => (new Query(name: 'item_query'))->withExtraProperties(['graphql_default_operation' => true]), + 'collection_query' => (new QueryCollection(name: 'collection_query'))->withExtraProperties(['graphql_default_operation' => true]), + ], true); + + $operations = $factory->create(\stdClass::class)[0]->getGraphQlOperations(); + + $this->assertSame(['item_query', 'collection_query'], array_keys($operations)); + $this->assertInstanceOf(QueryCollection::class, $operations['collection_query']); + $this->assertInstanceOf(Query::class, $operations['item_query']); + $this->assertTrue($operations['item_query']->getNested()); + $this->assertTrue($operations['collection_query']->getNested()); + $this->assertArrayNotHasKey('graphql_default_operation', $operations['item_query']->getExtraProperties()); + } + + public function testNestedOperationsReceiveTheGlobalDefaults(): void + { + $factory = $this->createFactory( + ['item_query' => (new Query(name: 'item_query'))->withExtraProperties(['graphql_default_operation' => true])], + true, + ['normalization_context' => ['skip_null_values' => true]] + ); + + $operations = $factory->create(\stdClass::class)[0]->getGraphQlOperations(); + + $this->assertSame(['skip_null_values' => true], $operations['collection_query']->getNormalizationContext()); + } + + public function testExplicitEmptyOperationsAreUntouched(): void + { + $operations = ['item_query' => (new Query(name: 'item_query'))->withNested(true)]; + $factory = $this->createFactory($operations, true); + + $this->assertSame($operations, $factory->create(\stdClass::class)[0]->getGraphQlOperations()); + } + + public function testSubtypeResourcesAreDetectedThroughTheirParentMap(): void + { + $decorated = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $decorated->method('create')->willReturn(new ResourceMetadataCollection(\UnexpectedValueException::class, [(new ApiResource(class: \UnexpectedValueException::class))->withGraphQlOperations(['item_query' => new Query(name: 'item_query')])])); + + $resolver = $this->createStub(ClassDiscriminatorResolverInterface::class); + $resolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => \RuntimeException::class === $class ? new ClassDiscriminatorMapping('kind', ['iterator' => \UnexpectedValueException::class]) : null); + + $this->expectException(RuntimeException::class); + + (new PolymorphicGraphQlResourceMetadataCollectionFactory($resolver, $decorated))->create(\UnexpectedValueException::class); + } + + public function testExplicitOperationsThrow(): void + { + $factory = $this->createFactory(['item_query' => new Query(name: 'item_query')], true); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(\sprintf('GraphQL is not supported yet for "%s", a resource with a discriminator map', \stdClass::class)); + + $factory->create(\stdClass::class); + } + + public function testNonPolymorphicResourcesAreUntouched(): void + { + $operations = ['item_query' => new Query(name: 'item_query')]; + $factory = $this->createFactory($operations, false); + + $this->assertSame($operations, $factory->create(\stdClass::class)[0]->getGraphQlOperations()); + } + + /** + * @param array $graphQlOperations + */ + private function createFactory(array $graphQlOperations, bool $hasMapping, array $defaults = []): PolymorphicGraphQlResourceMetadataCollectionFactory + { + $decorated = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $decorated->method('create')->willReturn(new ResourceMetadataCollection(\stdClass::class, [(new ApiResource(class: \stdClass::class))->withGraphQlOperations($graphQlOperations)])); + + $resolver = $this->createStub(ClassDiscriminatorResolverInterface::class); + $resolver->method('getMappingForClass')->willReturn($hasMapping ? new ClassDiscriminatorMapping('kind', ['standard' => \stdClass::class]) : null); + + return new PolymorphicGraphQlResourceMetadataCollectionFactory($resolver, $decorated, $defaults); + } +} diff --git a/src/Metadata/Tests/SubtypeResolverTest.php b/src/Metadata/Tests/SubtypeResolverTest.php new file mode 100644 index 00000000000..3f719969300 --- /dev/null +++ b/src/Metadata/Tests/SubtypeResolverTest.php @@ -0,0 +1,91 @@ + + * + * 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; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\Resource\ResourceNameCollection; +use ApiPlatform\Metadata\SubtypeResolver; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; + +class SubtypeResolverTest extends TestCase +{ + public function testSubtypes(): void + { + $resolver = $this->createResolver(); + + $this->assertSame(['car' => SubtypeResolverCar::class, 'truck' => SubtypeResolverTruck::class, 'bus' => SubtypeResolverBus::class], $resolver->getDirectSubtypes(SubtypeResolverVehicle::class)); + $this->assertSame([SubtypeResolverCar::class, SubtypeResolverTruck::class, SubtypeResolverHeavyTruck::class, SubtypeResolverBus::class], $resolver->getSubtypes(SubtypeResolverVehicle::class)); + // A map listing the class itself or an ancestor does not loop + $this->assertSame([SubtypeResolverHeavyTruck::class], $resolver->getSubtypes(SubtypeResolverTruck::class)); + } + + public function testTypeNames(): void + { + $resolver = $this->createResolver(); + + $this->assertSame('Vehicle', $resolver->getTypeName(SubtypeResolverVehicle::class)); + $this->assertSame(['Vehicle'], $resolver->getTypes(SubtypeResolverVehicle::class)); + $this->assertSame('Coach', $resolver->getTypeName(SubtypeResolverBus::class)); + $this->assertSame(['https://schema.org/BusOrCoach'], $resolver->getTypes(SubtypeResolverBus::class)); + $this->assertSame('SubtypeResolverCar', $resolver->getTypeName(SubtypeResolverCar::class)); + $this->assertSame(['SubtypeResolverCar'], $resolver->getTypes(SubtypeResolverCar::class)); + } + + private function createResolver(): SubtypeResolver + { + $mappings = [ + SubtypeResolverVehicle::class => new ClassDiscriminatorMapping('kind', ['car' => SubtypeResolverCar::class, 'truck' => SubtypeResolverTruck::class, 'bus' => SubtypeResolverBus::class]), + SubtypeResolverTruck::class => new ClassDiscriminatorMapping('size', ['vehicle' => SubtypeResolverVehicle::class, 'truck' => SubtypeResolverTruck::class, 'heavy' => SubtypeResolverHeavyTruck::class]), + ]; + $classDiscriminatorResolver = $this->createStub(ClassDiscriminatorResolverInterface::class); + $classDiscriminatorResolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => $mappings[$class] ?? null); + + $resources = [ + SubtypeResolverVehicle::class => new ApiResource(shortName: 'Vehicle'), + SubtypeResolverBus::class => new ApiResource(shortName: 'Coach', types: ['https://schema.org/BusOrCoach']), + ]; + $resourceNameCollectionFactory = $this->createStub(ResourceNameCollectionFactoryInterface::class); + $resourceNameCollectionFactory->method('create')->willReturn(new ResourceNameCollection(array_keys($resources))); + + $resourceMetadataCollectionFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $resourceMetadataCollectionFactory->method('create')->willReturnCallback(static fn (string $class): ResourceMetadataCollection => new ResourceMetadataCollection($class, [$resources[$class]])); + + return new SubtypeResolver($classDiscriminatorResolver, $resourceNameCollectionFactory, $resourceMetadataCollectionFactory); + } +} + +class SubtypeResolverVehicle +{ +} + +class SubtypeResolverCar extends SubtypeResolverVehicle +{ +} + +class SubtypeResolverTruck extends SubtypeResolverVehicle +{ +} + +class SubtypeResolverHeavyTruck extends SubtypeResolverTruck +{ +} + +class SubtypeResolverBus extends SubtypeResolverVehicle +{ +} diff --git a/src/Metadata/composer.json b/src/Metadata/composer.json index 981f04ceef4..5b59dd4b680 100644 --- a/src/Metadata/composer.json +++ b/src/Metadata/composer.json @@ -44,6 +44,7 @@ "phpunit/phpunit": "^11.5 || ^12.2 || ^13.0", "symfony/config": "^7.4 || ^8.0", "symfony/routing": "^7.4 || ^8.0", + "symfony/serializer": "^7.4 || ^8.0", "symfony/var-dumper": "^7.4 || ^8.0", "symfony/web-link": "^7.4 || ^8.0", "symfony/yaml": "^7.4 || ^8.0" @@ -51,7 +52,8 @@ "suggest": { "phpstan/phpdoc-parser": "For PHP documentation support.", "symfony/yaml": "For YAML resource configuration.", - "symfony/config": "For XML resource configuration." + "symfony/config": "For XML resource configuration.", + "symfony/serializer": "For resource polymorphism through serializer discriminator maps." }, "autoload": { "psr-4": { diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index 7048a670927..b37089f1a54 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -25,9 +25,12 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Metadata\Util\CloneTrait; +use ApiPlatform\State\Exception\UnprocessableValueException; +use ApiPlatform\State\SerializerContextBuilderInterface; use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException as PropertyAccessInvalidArgumentException; use Symfony\Component\PropertyAccess\Exception\InvalidTypeException; use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; @@ -41,6 +44,7 @@ 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\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; @@ -75,6 +79,7 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement * when normalizing or omitted. */ public const SKIP_NULL_TO_ONE_RELATIONS = 'skip_null_to_one_relations'; + private const TYPE_PROPERTY_FORMAT = 'api_type_property_format'; protected PropertyAccessorInterface $propertyAccessor; protected array $localCache = []; @@ -83,7 +88,13 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement protected array $attributesCache = []; protected ?ResourceAccessCheckerInterface $resourceAccessChecker; - 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) + /** @var array, typeMappings: array}|null> */ + private array $discriminatorMappingCache = []; + + /** @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, protected readonly ?SubtypeResolverInterface $subtypeResolver = null) { if (!isset($defaultContext['circular_reference_handler'])) { $defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object); @@ -248,6 +259,8 @@ public function supportsDenormalization(mixed $data, string $type, ?string $form public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed { $resourceClass = $type; + $replacedClass = $context[SerializerContextBuilderInterface::REPLACED_CLASS] ?? null; + unset($context[SerializerContextBuilderInterface::REPLACED_CLASS]); if ($inputClass = $this->getInputClass($context)) { if (!$this->serializer instanceof DenormalizerInterface) { @@ -269,7 +282,17 @@ 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); + $resolvedTypes = []; + $replacedRealClass = \is_string($replacedClass) ? $this->getRealClassName($replacedClass) : null; + do { + $resolvedTypes[$type] = true; + if (null !== $this->subtypeResolver && null !== $replacedRealClass && is_a($replacedRealClass, $type, true) && null !== ($typeMapping = $this->classDiscriminatorResolver?->getMappingForClass($type)) && !isset($normalizedData[$this->getTypePropertyKey($typeMapping->getTypeProperty(), $type, $format, $context)])) { + $type = $replacedRealClass; + break; + } + + $type = $this->getClassDiscriminatorResolvedClass($normalizedData, $type, $context + [self::TYPE_PROPERTY_FORMAT => $format]); + } while (null !== $this->subtypeResolver && !isset($resolvedTypes[$type])); } $context['api_denormalize'] = true; @@ -277,6 +300,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; + + if (\is_array($data) && null !== $discriminatorMapping = $this->getDiscriminatorMapping($resourceClass, null !== $objectToPopulate ? $this->getObjectClass($objectToPopulate) : $type)) { + $data = $this->prepareDiscriminatedData($data, $discriminatorMapping, null !== $objectToPopulate ? $this->getObjectClass($objectToPopulate) : null, \is_string($replacedClass) ? $this->getRealClassName($replacedClass) : null, $type, $resourceClass, $context, $format); + $resourceClass = $context['resource_class'] = $discriminatorMapping['class']; + } elseif (\is_array($data) && null !== ($existingClass = null !== $objectToPopulate ? $this->getObjectClass($objectToPopulate) : (\is_string($replacedClass) ? $this->getRealClassName($replacedClass) : null))) { + $this->validateTypeAgainstParentMappings($data, $existingClass, $context, $format); + } } 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 @@ -404,7 +434,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex return $object; } - $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context); + $class = $this->getClassDiscriminatorResolvedClass($data, $class, $context + [self::TYPE_PROPERTY_FORMAT => $format]); $reflectionClass = new \ReflectionClass($class); $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes); @@ -498,11 +528,12 @@ protected function getClassDiscriminatorResolvedClass(array $data, string $class // @phpstan-ignore-next-line function.alreadyNarrowedType $defaultType = method_exists($mapping, 'getDefaultType') ? $mapping->getDefaultType() : null; - if (!isset($data[$mapping->getTypeProperty()]) && null === $defaultType) { + $typeKey = $this->getTypePropertyKey($mapping->getTypeProperty(), $class, $context[self::TYPE_PROPERTY_FORMAT] ?? null, $context); + if (!isset($data[$typeKey]) && null === $defaultType) { throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('Type property "%s" not found for the abstract object "%s".', $mapping->getTypeProperty(), $class), null, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty()); } - $type = $data[$mapping->getTypeProperty()] ?? $defaultType; + $type = $data[$typeKey] ?? $defaultType; if (!\is_string($type)) { throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type property "%s" for the abstract object "%s" must be a string.', $mapping->getTypeProperty(), $class), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty()); } @@ -514,6 +545,157 @@ protected function getClassDiscriminatorResolvedClass(array $data, string $class return $mappedClass; } + private function getTypePropertyKey(string $typeProperty, string $class, ?string $format, array $context): string + { + return $this->nameConverter?->normalize($typeProperty, $class, $format, $context) ?? $typeProperty; + } + + /** + * @return array{class: class-string, mappings: list, typeMappings: array}|null + */ + private function getDiscriminatorMapping(string $resourceClass, string $class): ?array + { + if (null === $this->subtypeResolver) { + return null; + } + + $cacheKey = $resourceClass.'|'.$class; + if (!\array_key_exists($cacheKey, $this->discriminatorMappingCache)) { + $this->discriminatorMappingCache[$cacheKey] = $this->resolveDiscriminatorMapping($this->subtypeResolver, $resourceClass, $class); + } + + return $this->discriminatorMappingCache[$cacheKey]; + } + + /** + * Walks the maps of the resource down to the most specific mapped class: an unmapped subclass resolves to its closest mapped parent. + * + * @return array{class: class-string, mappings: list, typeMappings: array}|null + */ + private function resolveDiscriminatorMapping(SubtypeResolverInterface $subtypeResolver, string $resourceClass, string $class): ?array + { + if (!is_a($class, $resourceClass, true)) { + return null; + } + + $mappedClass = $resourceClass; + $mappings = []; + $typeMappings = []; + while (null !== $mapping = $subtypeResolver->getMapping($mappedClass)) { + $candidate = null; + foreach ($subtypeResolver->getDirectSubtypes($mappedClass) as $subtype) { + if (is_a($class, $subtype, true) && (null === $candidate || is_a($subtype, $candidate, true))) { + $candidate = $subtype; + } + } + + if (null === $candidate && !\in_array($mappedClass, $mapping->getTypesMapping(), true)) { + break; + } + + $mappings[] = $mapping; + $typeMappings[$mapping->getTypeProperty()] ??= $mapping; + if (null === $candidate) { + break; + } + + $mappedClass = $candidate; + } + + return $mappings ? ['class' => $mappedClass, 'mappings' => $mappings, 'typeMappings' => $typeMappings] : null; + } + + /** + * @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, mappings: list, typeMappings: array} $discriminatorMapping + */ + private function prepareDiscriminatedData(array $data, array $discriminatorMapping, ?string $populatedClass, ?string $replacedClass, string $type, string $resourceClass, array $context, ?string $format): array + { + $existingClass = $populatedClass ?? $replacedClass; + // A class declaring its own map is resolved again by the Symfony serializer, which reads the type property of that map + $resolvedTypeProperty = null === $populatedClass ? $this->subtypeResolver?->getMapping($type)?->getTypeProperty() : null; + foreach ($discriminatorMapping['mappings'] as $mapping) { + $typeProperty = $mapping->getTypeProperty(); + $typeKey = $this->getTypePropertyKey($typeProperty, $type, $format, $context); + if (!\array_key_exists($typeKey, $data)) { + continue; + } + + if (null !== $existingClass && (!\is_string($data[$typeKey]) || $mapping->getClassForType($data[$typeKey]) !== $this->getMostSpecificMappedClass($mapping, $existingClass))) { + throw $this->createTypeChangeException($data[$typeKey], $typeKey, $context); + } + + if ($typeProperty !== $resolvedTypeProperty && !property_exists($discriminatorMapping['class'], $typeProperty)) { + unset($data[$typeKey]); + } + } + + if (null !== $replacedClass && null !== ($replacedMapping = $this->getDiscriminatorMapping($resourceClass, $replacedClass)) && $replacedMapping['class'] !== $discriminatorMapping['class']) { + $typeKey = $this->getTypePropertyKey(end($replacedMapping['mappings'])->getTypeProperty(), $type, $format, $context); + + throw $this->createTypeChangeException($data[$typeKey] ?? null, $typeKey, $context); + } + + return $data; + } + + private function validateTypeAgainstParentMappings(array $data, string $existingClass, array $context, ?string $format): void + { + if (null === $this->subtypeResolver) { + return; + } + + for ($class = $existingClass; false !== $class; $class = get_parent_class($class)) { + if (null === ($mapping = $this->subtypeResolver->getMapping($class)) || !\array_key_exists($typeKey = $this->getTypePropertyKey($mapping->getTypeProperty(), $class, $format, $context), $data)) { + continue; + } + + if (!\is_string($data[$typeKey]) || $mapping->getClassForType($data[$typeKey]) !== $this->getMostSpecificMappedClass($mapping, $existingClass)) { + throw $this->createTypeChangeException($data[$typeKey], $typeKey, $context); + } + } + } + + private function createTypeChangeException(mixed $value, string $typeProperty, array $context): UnprocessableValueException + { + return new UnprocessableValueException(\sprintf('The type "%s" does not match the type of the resource being updated.', \is_scalar($value) ? $value : get_debug_type($value)), $value, isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$typeProperty : $typeProperty, UnprocessableValueException::TYPE_MISMATCH_ERROR); + } + + /** + * 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, string $objectClass): ?string + { + $mostSpecificClass = null; + foreach ($mapping->getTypesMapping() as $class) { + if (is_a($objectClass, $class, true) && (null === $mostSpecificClass || is_a($class, $mostSpecificClass, true))) { + $mostSpecificClass = $class; + } + } + + return $mostSpecificClass; + } + + private function getDiscriminatorTypeValue(object $object, string $attribute, string $contextClass): ?string + { + if (null === $this->subtypeResolver || !$this->resourceClassResolver->isResourceClass($contextClass)) { + return null; + } + + $mapping = $this->getDiscriminatorMapping($this->resourceClassResolver->getResourceClass(null, $contextClass), $this->getObjectClass($object))['typeMappings'][$attribute] ?? null; + + return $mapping?->getMappedObjectType($object); + } + protected function createConstructorArgument(mixed $parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed { return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context); @@ -541,6 +723,12 @@ protected function getAllowedAttributes(string|object $classOrObject, array $con } $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces + // Only the subtypes declared in a discriminator map of the resource are exposed + $discriminatorMapping = $this->getDiscriminatorMapping($resourceClass, \is_object($classOrObject) ? $this->getObjectClass($classOrObject) : $context['resource_class']); + if (null !== $discriminatorMapping) { + $resourceClass = $discriminatorMapping['class']; + } + $options = $this->getFactoryOptions($context); $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options); @@ -558,6 +746,19 @@ protected function getAllowedAttributes(string|object $classOrObject, array $con } } + if (null !== $discriminatorMapping && isset($context['api_normalize'])) { + foreach (array_reverse(array_keys($discriminatorMapping['typeMappings'])) as $typeProperty) { + if (!\in_array($typeProperty, $allowedAttributes, true) && $this->isAllowedAttribute($classOrObject, $typeProperty, null, $context)) { + array_unshift($allowedAttributes, $typeProperty); + } + } + } + + // The serializer reads the type property of the map declared by the class being created to resolve it + if (isset($context['api_denormalize']) && \is_string($classOrObject) && null !== ($typeProperty = $this->subtypeResolver?->getMapping($classOrObject)?->getTypeProperty()) && !\in_array($typeProperty, $allowedAttributes, true)) { + $allowedAttributes[] = $typeProperty; + } + return $allowedAttributes; } @@ -640,14 +841,13 @@ 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; + foreach ([$resourceClass, ...($this->subtypeResolver?->getSubtypes($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; + } } } @@ -678,6 +878,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->subtypeResolver && $attribute === ($this->discriminatorTypePropertyCache[$this->getObjectClass($object)] ??= $this->classDiscriminatorResolver?->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) @@ -887,6 +1092,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/Serializer/ItemDenormalizer.php b/src/Serializer/ItemDenormalizer.php index 288bf3e20ec..91991a558ac 100644 --- a/src/Serializer/ItemDenormalizer.php +++ b/src/Serializer/ItemDenormalizer.php @@ -19,6 +19,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -36,9 +37,9 @@ class ItemDenormalizer extends AbstractItemNormalizer private readonly LoggerInterface $logger; - public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null) + public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, ?SubtypeResolverInterface $subtypeResolver = null) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); $this->logger = $logger ?: new NullLogger(); } diff --git a/src/Serializer/ItemNormalizer.php b/src/Serializer/ItemNormalizer.php index 0d683eca5da..66208a6a956 100644 --- a/src/Serializer/ItemNormalizer.php +++ b/src/Serializer/ItemNormalizer.php @@ -19,6 +19,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolverInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -40,9 +41,9 @@ class ItemNormalizer extends AbstractItemNormalizer private readonly LoggerInterface $logger; - public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null) + public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null, ?OperationResourceClassResolverInterface $operationResourceResolver = null, ?SubtypeResolverInterface $subtypeResolver = null) { - parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver); + parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver, $subtypeResolver); $this->logger = $logger ?: new NullLogger(); } diff --git a/src/Serializer/composer.json b/src/Serializer/composer.json index 033a92ada52..bcdbb73e40a 100644 --- a/src/Serializer/composer.json +++ b/src/Serializer/composer.json @@ -23,8 +23,8 @@ ], "require": { "php": ">=8.2", - "api-platform/metadata": "^5.0", - "api-platform/state": "^5.0", + "api-platform/metadata": "^5.1", + "api-platform/state": "^5.1", "symfony/property-access": "^7.4 || ^8.0", "symfony/property-info": "^7.4 || ^8.0", "symfony/serializer": "^7.4.9 || ^8.0.9", diff --git a/src/State/Exception/UnprocessableValueException.php b/src/State/Exception/UnprocessableValueException.php new file mode 100644 index 00000000000..9e8b9f91125 --- /dev/null +++ b/src/State/Exception/UnprocessableValueException.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\State\Exception; + +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; + +/** + * A well-formed value the API refuses, reported as a validation violation (422) at its path. + */ +final class UnprocessableValueException extends NotNormalizableValueException +{ + public const TYPE_MISMATCH_ERROR = '13ff6cd3-d9ac-451a-af4a-846e8e36056f'; + + public function __construct(string $message, mixed $value, string $path, private readonly string $violationCode) + { + parent::__construct($message, 0, null, get_debug_type($value), null, $path, true); + } + + public function getViolationCode(): string + { + return $this->violationCode; + } +} diff --git a/src/State/ObjectMapper/SubtypeObjectMapper.php b/src/State/ObjectMapper/SubtypeObjectMapper.php new file mode 100644 index 00000000000..962afb26fff --- /dev/null +++ b/src/State/ObjectMapper/SubtypeObjectMapper.php @@ -0,0 +1,194 @@ + + * + * 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\State\ObjectMapper; + +use ApiPlatform\Metadata\Exception\RuntimeException; +use ApiPlatform\Metadata\SubtypeResolverInterface; +use Symfony\Component\ObjectMapper\Attribute\Map; +use Symfony\Component\ObjectMapper\Exception\MappingException; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +trait SubtypeObjectMapperTrait +{ + /** @var array */ + private array $abstractCache = []; + /** @var array, 1: list}> */ + private array $candidatesCache = []; + + private function resolveTarget(object $source, object|string|null $target): object|string|null + { + if (!\is_string($target) || !($this->abstractCache[$target] ??= $this->isAbstract($target))) { + return $target; + } + + [$written, $read] = $this->candidatesCache[$source::class.'::'.$target] ??= $this->findCandidates($source, $target); + + $written = $this->filter($written, $source, $target); + $classes = array_values(array_unique(array_column($written, 0))); + if (1 === \count($classes)) { + return $classes[0]; + } + + if ($classes) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": ambiguous target, candidates are "%s".', $source::class, $this->kind($target), $target, implode('", "', $classes))); + } + + $read = $this->filter($read, $source, $target); + if (!$read) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": no subclass of "%s" maps from it.', $source::class, $this->kind($target), $target, $target)); + } + + $survivors = array_filter($read, static function (array $candidate) use ($read): bool { + foreach ($read as $other) { + if ($other[2] !== $candidate[2] && is_subclass_of($other[2], $candidate[2])) { + return false; + } + } + + return true; + }); + $classes = array_values(array_unique(array_column($survivors, 0))); + + if (\count($classes) > 1) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": ambiguous subclasses, candidates are "%s".', $source::class, $this->kind($target), $target, implode('", "', $classes))); + } + + return $classes[0]; + } + + /** + * @return array{0: list, 1: list} candidates from the mappings of the source then from the subclasses, as [concrete class, "if" condition, mapped source class] + */ + private function findCandidates(object $source, string $target): array + { + $written = []; + foreach ($this->objectMapperMetadata->create($source) as $mapping) { + if (\is_string($mapping->target) && $this->isInstantiable($mapping->target) && is_a($mapping->target, $target, true)) { + $written[] = [$mapping->target, $mapping->if, null]; + } + } + + $read = []; + foreach ($this->subtypeResolver->getSubtypes($target) as $subtype) { + if (!$this->isInstantiable($subtype)) { + continue; + } + + foreach ((new \ReflectionClass($subtype))->getAttributes(Map::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { + $map = $attribute->newInstance(); + if (\is_string($map->source) && is_a($source, $map->source, true)) { + $read[] = [$subtype, $map->if, $map->source]; + } + } + } + + return [$written, $read]; + } + + /** + * @param list $candidates + * + * @return list + */ + private function filter(array $candidates, object $source, string $abstract): array + { + return array_values(array_filter($candidates, fn (array $candidate): bool => $this->passes($candidate[1], $source, $candidate[0], $candidate[2], $abstract))); + } + + private function passes(mixed $if, object $source, string $target, ?string $mappedSource, string $abstract): bool + { + if (null === $if || true === $if) { + return true; + } + + if (false === $if) { + return false; + } + + if (!\is_callable($if)) { + throw new MappingException(\sprintf('Cannot evaluate the "if" condition of the mapping from "%s" to "%s": service conditions are not supported when mapping to an %s.', $mappedSource ?? $source::class, $target, $this->kind($abstract))); + } + + return \is_string($if) ? (bool) \call_user_func($if, null) : (bool) $if(null, $source, null); + } + + private function kind(string $class): string + { + return interface_exists($class) ? 'interface' : 'abstract class'; + } + + private function isAbstract(string $class): bool + { + return (class_exists($class) || interface_exists($class)) && !(new \ReflectionClass($class))->isInstantiable(); + } + + private function isInstantiable(string $class): bool + { + return class_exists($class) && (new \ReflectionClass($class))->isInstantiable(); + } +} + +if (false === interface_exists(ObjectMapperAwareInterface::class)) { + final class SubtypeObjectMapper implements ObjectMapperInterface + { + use SubtypeObjectMapperTrait; + + public function __construct( + private ObjectMapperInterface $decorated, + private readonly SubtypeResolverInterface $subtypeResolver, + private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + ) { + } + + public function map(object $source, object|string|null $target = null): object + { + return $this->decorated->map($source, $this->resolveTarget($source, $target)); + } + } +} else { + final class SubtypeObjectMapper implements ObjectMapperInterface, ObjectMapperAwareInterface + { + use SubtypeObjectMapperTrait; + + public function __construct( + private ObjectMapperInterface $decorated, + private readonly SubtypeResolverInterface $subtypeResolver, + private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + ) { + if ($this->decorated instanceof ObjectMapperAwareInterface) { + $this->decorated = $this->decorated->withObjectMapper($this); + } + } + + public function map(object $source, object|string|null $target = null): object + { + return $this->decorated->map($source, $this->resolveTarget($source, $target)); + } + + public function withObjectMapper(ObjectMapperInterface $objectMapper): static + { + $s = clone $this; + + if (!$s->decorated instanceof ObjectMapperAwareInterface) { + throw new RuntimeException(\sprintf('Given object mapper "%s" does not implements %s.', get_debug_type($this->decorated), ObjectMapperAwareInterface::class)); + } + + $s->decorated = $s->decorated->withObjectMapper($objectMapper); + + return $s; + } + } +} diff --git a/src/State/Provider/DeserializeProvider.php b/src/State/Provider/DeserializeProvider.php index d91b26a475d..378cdc0e9ea 100644 --- a/src/State/Provider/DeserializeProvider.php +++ b/src/State/Provider/DeserializeProvider.php @@ -71,6 +71,8 @@ public function provide(Operation $operation, array $uriVariables = [], array $c if (null !== $data && ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? false)) { $serializerContext[AbstractNormalizer::OBJECT_TO_POPULATE] = $data; + } elseif (\is_object($data) && 'PUT' === $operation->getMethod()) { + $serializerContext[SerializerContextBuilderInterface::REPLACED_CLASS] = $data::class; } unset($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE]); diff --git a/src/State/SerializerContextBuilderInterface.php b/src/State/SerializerContextBuilderInterface.php index 99247373712..ef70685347a 100644 --- a/src/State/SerializerContextBuilderInterface.php +++ b/src/State/SerializerContextBuilderInterface.php @@ -27,6 +27,13 @@ interface SerializerContextBuilderInterface // @see ApiPlatform\Symfony\Controller\MainController and ApiPlatform\State\Provider\DeserializerProvider public const ASSIGN_OBJECT_TO_POPULATE = 'api_assign_object_to_populate'; + /** + * The class of the resource a PUT replaces, set by ApiPlatform\State\Provider\DeserializeProvider. + * + * @internal + */ + public const REPLACED_CLASS = 'api_replaced_class'; + /** * Creates a serialization context from a Request. * diff --git a/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php b/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php new file mode 100644 index 00000000000..aa20907457b --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.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\State\Tests\Fixtures\ObjectMapper; + +abstract class AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php b/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php new file mode 100644 index 00000000000..b72a473cb38 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class)] +#[Map(target: SecondConcreteTarget::class)] +final class AmbiguousWriteSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/CarSource.php b/src/State/Tests/Fixtures/ObjectMapper/CarSource.php new file mode 100644 index 00000000000..f1472d5f0df --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/CarSource.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\State\Tests\Fixtures\ObjectMapper; + +class CarSource extends VehicleSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php b/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php new file mode 100644 index 00000000000..ecbb7b3972b --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class, if: [DenyingCondition::class, 'deny'])] +#[Map(target: SecondConcreteTarget::class)] +final class ConditionalWriteSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php b/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php new file mode 100644 index 00000000000..dbb64753d6c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.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\State\Tests\Fixtures\ObjectMapper; + +final class DenyingCondition +{ + public static function deny(mixed $value, object $source, ?object $target): bool + { + return false; + } +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php b/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php new file mode 100644 index 00000000000..458e459cabb --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.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\State\Tests\Fixtures\ObjectMapper; + +final class FirstConcreteTarget extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php b/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php new file mode 100644 index 00000000000..60329bd0a09 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.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\State\Tests\Fixtures\ObjectMapper; + +final class InterfaceAndParentSource extends ParentSource implements ReadableSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ParentSource.php b/src/State/Tests/Fixtures/ObjectMapper/ParentSource.php new file mode 100644 index 00000000000..dec212e2c51 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ParentSource.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\State\Tests\Fixtures\ObjectMapper; + +class ParentSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php b/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php new file mode 100644 index 00000000000..88a95658b4d --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.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\State\Tests\Fixtures\ObjectMapper; + +interface ReadableSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php b/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php new file mode 100644 index 00000000000..028b20cbd49 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.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\State\Tests\Fixtures\ObjectMapper; + +final class SecondConcreteTarget extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php b/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php new file mode 100644 index 00000000000..3ada58d06c8 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class, if: 'app.condition')] +final class ServiceConditionSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php b/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php new file mode 100644 index 00000000000..90b1287adee --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.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\State\Tests\Fixtures\ObjectMapper; + +final class SportsCarSource extends CarSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php b/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php new file mode 100644 index 00000000000..0097dc85b77 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: CarSource::class, if: [DenyingCondition::class, 'deny'])] +final class TargetDeniedFromCar extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php new file mode 100644 index 00000000000..16635ab1673 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: CarSource::class)] +final class TargetMappedFromCar extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php new file mode 100644 index 00000000000..4160709d45c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: ReadableSource::class)] +final class TargetMappedFromInterface extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php new file mode 100644 index 00000000000..954f9605743 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: ParentSource::class)] +final class TargetMappedFromParent extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php new file mode 100644 index 00000000000..7370397439c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.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\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: VehicleSource::class)] +final class TargetMappedFromVehicle extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php b/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php new file mode 100644 index 00000000000..ad6baaf16b7 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.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\State\Tests\Fixtures\ObjectMapper; + +final class UnmappedSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php b/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php new file mode 100644 index 00000000000..0dbde2f086f --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.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\State\Tests\Fixtures\ObjectMapper; + +class VehicleSource +{ +} diff --git a/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php b/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php new file mode 100644 index 00000000000..b210ecd0b3d --- /dev/null +++ b/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php @@ -0,0 +1,152 @@ + + * + * 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\State\Tests\ObjectMapper; + +use ApiPlatform\Metadata\SubtypeResolverInterface; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\AbstractMappedTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\AmbiguousWriteSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ConditionalWriteSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\FirstConcreteTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\InterfaceAndParentSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ReadableSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\SecondConcreteTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ServiceConditionSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\SportsCarSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetDeniedFromCar; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromCar; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromInterface; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromParent; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromVehicle; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\UnmappedSource; +use PHPUnit\Framework\TestCase; +use Symfony\Component\ObjectMapper\Exception\MappingException; +use Symfony\Component\ObjectMapper\Metadata\Mapping; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +final class SubtypeObjectMapperTest extends TestCase +{ + public function testAmbiguousWriteTargets(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('"%s", "%s"', FirstConcreteTarget::class, SecondConcreteTarget::class)); + + $this->createMapper($decorated, $resolver)->map(new AmbiguousWriteSource(), AbstractMappedTarget::class); + } + + public function testNoSubclassMapsFromSource(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetMappedFromCar::class]); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot map "%s" to the abstract class "%s": no subclass of "%s" maps from it.', UnmappedSource::class, AbstractMappedTarget::class, AbstractMappedTarget::class)); + + $this->createMapper($decorated, $resolver)->map(new UnmappedSource(), AbstractMappedTarget::class); + } + + public function testClosestParentSourceWins(): void + { + $source = new SportsCarSource(); + $expected = new TargetMappedFromCar(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, TargetMappedFromCar::class)->willReturn($expected); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetMappedFromCar::class]); + + $this->assertSame($expected, $this->createMapper($decorated, $resolver)->map($source, AbstractMappedTarget::class)); + } + + public function testInterfaceAndParentSourcesAreAmbiguous(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromInterface::class, TargetMappedFromParent::class]); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('"%s", "%s"', TargetMappedFromInterface::class, TargetMappedFromParent::class)); + + $this->createMapper($decorated, $resolver)->map(new InterfaceAndParentSource(), AbstractMappedTarget::class); + } + + public function testFalseConditionExcludesWriteCandidate(): void + { + $source = new ConditionalWriteSource(); + $expected = new SecondConcreteTarget(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, SecondConcreteTarget::class)->willReturn($expected); + + $this->assertSame($expected, $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map($source, AbstractMappedTarget::class)); + } + + public function testFalseConditionExcludesReadCandidate(): void + { + $source = new SportsCarSource(); + $expected = new TargetMappedFromVehicle(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, TargetMappedFromVehicle::class)->willReturn($expected); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetDeniedFromCar::class]); + + $this->assertSame($expected, $this->createMapper($decorated, $resolver)->map($source, AbstractMappedTarget::class)); + } + + public function testServiceConditionIsRejected(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot evaluate the "if" condition of the mapping from "%s" to "%s": service conditions are not supported when mapping to an abstract class.', ServiceConditionSource::class, FirstConcreteTarget::class)); + + $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map(new ServiceConditionSource(), AbstractMappedTarget::class); + } + + public function testResolutionIsCached(): void + { + $metadata = $this->createMock(ObjectMapperMetadataFactoryInterface::class); + $metadata->expects($this->once())->method('create')->willReturn([new Mapping(FirstConcreteTarget::class)]); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->exactly(2))->method('map')->with($this->anything(), FirstConcreteTarget::class)->willReturn(new FirstConcreteTarget()); + + $mapper = new SubtypeObjectMapper($decorated, $this->createStub(SubtypeResolverInterface::class), $metadata); + $mapper->map(new UnmappedSource(), AbstractMappedTarget::class); + $mapper->map(new UnmappedSource(), AbstractMappedTarget::class); + } + + public function testInterfaceTargetIsNamedInTheMessage(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot map "%s" to the interface "%s"', UnmappedSource::class, ReadableSource::class)); + + $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map(new UnmappedSource(), ReadableSource::class); + } + + private function createMapper(ObjectMapperInterface $decorated, SubtypeResolverInterface $resolver): SubtypeObjectMapper + { + return new SubtypeObjectMapper($decorated, $resolver, new ReflectionObjectMapperMetadataFactory()); + } +} diff --git a/src/State/composer.json b/src/State/composer.json index 3171c9c6514..e959456bc1c 100644 --- a/src/State/composer.json +++ b/src/State/composer.json @@ -28,7 +28,7 @@ ], "require": { "php": ">=8.2", - "api-platform/metadata": "^5.0", + "api-platform/metadata": "^5.1", "psr/container": "^1.0 || ^2.0", "symfony/http-kernel": "^7.4 || ^8.0", "symfony/serializer": "^7.4 || ^8.0", diff --git a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php index 56772b97979..f5c39c29a70 100644 --- a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php @@ -215,6 +215,10 @@ public function load(array $configs, ContainerBuilder $container): void if (class_exists(ObjectMapper::class) && ContainerBuilder::willBeAvailable('symfony/object-mapper', ObjectMapperInterface::class, ['symfony/framework-bundle'])) { $loader->load('state/object_mapper.php'); $loader->load($config['use_symfony_listeners'] ? 'symfony/object_mapper.php' : 'state/object_mapper_processor.php'); + + if (!$container->hasDefinition('api_platform.serializer.subtype_resolver')) { + $container->removeDefinition('api_platform.object_mapper.subtype'); + } } $container->setParameter('api_platform.mcp.format', $config['mcp']['format'] ?? null); @@ -349,6 +353,17 @@ private function registerCommonConfiguration(ContainerBuilder $container, array $container->setDefinition('serializer.normalizer.number', $numberNormalizerDefinition); } + // Doctrine discriminator maps are exposed as serializer discriminator maps: they need resource polymorphism + if (!$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->removeDefinition('api_platform.serializer.subtype_resolver'); + $container->setParameter('api_platform.serializer.resource_polymorphism', false); + } else { + $container->setParameter('api_platform.serializer.resource_polymorphism', true); + } + $defaultContext = ['hydra_prefix' => $config['serializer']['hydra_prefix']] + ($container->hasParameter('serializer.default_context') ? $container->getParameter('serializer.default_context') : []); $container->setParameter('api_platform.serializer.default_context', $defaultContext); @@ -489,6 +504,9 @@ private function registerMetadataConfiguration(ContainerBuilder $container, arra $loader->load('metadata/links.php'); $loader->load('metadata/property.php'); $loader->load('metadata/resource.php'); + if (!$container->hasDefinition('api_platform.serializer.subtype_resolver')) { + $container->removeDefinition('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql'); + } $loader->load('metadata/operation.php'); $loader->load('metadata/mutator.php'); @@ -867,6 +885,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; } @@ -901,6 +923,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..5dd58eba4f0 100644 --- a/src/Symfony/Bundle/Resources/config/api.php +++ b/src/Symfony/Bundle/Resources/config/api.php @@ -20,6 +20,7 @@ use ApiPlatform\Metadata\Operation\UnderscorePathSegmentNameGenerator; use ApiPlatform\Metadata\ResourceClassResolver; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\SubtypeResolver; use ApiPlatform\Metadata\UriVariablesConverter; use ApiPlatform\Metadata\UriVariableTransformer\ApiResourceUriVariableTransformer; use ApiPlatform\Metadata\UriVariableTransformer\DateTimeUriVariableTransformer; @@ -160,6 +161,13 @@ $services->set('api_platform.serializer.operation_resource_resolver', OperationResourceClassResolver::class); $services->alias(OperationResourceClassResolverInterface::class, 'api_platform.serializer.operation_resource_resolver'); + $services->set('api_platform.serializer.subtype_resolver', SubtypeResolver::class) + ->args([ + service('serializer.mapping.class_discriminator_resolver'), + service('api_platform.metadata.resource.name_collection_factory'), + service('api_platform.metadata.resource.metadata_collection_factory'), + ]); + $services->set('api_platform.serializer.normalizer.item', ItemNormalizer::class) ->args([ service('api_platform.metadata.property.name_collection_factory'), @@ -176,6 +184,7 @@ service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -895]) ->tag('kernel.reset', ['method' => '?reset']); @@ -195,6 +204,7 @@ service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -894]) ->tag('kernel.reset', ['method' => '?reset']); 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..2be5d2d8f1a 100644 --- a/src/Symfony/Bundle/Resources/config/hal.php +++ b/src/Symfony/Bundle/Resources/config/hal.php @@ -66,6 +66,7 @@ service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -890]) ->tag('kernel.reset', ['method' => '?reset']); diff --git a/src/Symfony/Bundle/Resources/config/hydra.php b/src/Symfony/Bundle/Resources/config/hydra.php index 1ce0d98c9d5..d58cec024d4 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.subtype_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..fd1faea77e6 100644 --- a/src/Symfony/Bundle/Resources/config/json_schema.php +++ b/src/Symfony/Bundle/Resources/config/json_schema.php @@ -31,7 +31,9 @@ service('api_platform.name_converter')->ignoreOnInvalid(), service('api_platform.resource_class_resolver'), service('api_platform.json_schema.definition_name_factory')->ignoreOnInvalid(), - ]); + service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(), + ]) + ->arg('$resourcePolymorphism', '%api_platform.serializer.resource_polymorphism%'); $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..c4c51c56111 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.subtype_resolver')->ignoreOnInvalid(), ]); $services->set('api_platform.jsonapi.encoder', JsonEncoder::class) @@ -84,6 +85,7 @@ service('api_platform.serializer.operation_resource_resolver'), service('api_platform.api.identifiers_extractor'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -890]) ->tag('kernel.reset', ['method' => '?reset']); @@ -102,6 +104,7 @@ service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -889]) ->tag('kernel.reset', ['method' => '?reset']); diff --git a/src/Symfony/Bundle/Resources/config/jsonld.php b/src/Symfony/Bundle/Resources/config/jsonld.php index 368295f0ea8..ac34b50c59f 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.subtype_resolver')->ignoreOnInvalid(), ]); $services->set('api_platform.jsonld.normalizer.item', ItemNormalizer::class) @@ -53,6 +54,7 @@ service('api_platform.metadata.operation.metadata_factory')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -890]) ->tag('kernel.reset', ['method' => '?reset']); @@ -71,6 +73,7 @@ service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) + ->arg('$subtypeResolver', service('api_platform.serializer.subtype_resolver')->ignoreOnInvalid()) ->tag('serializer.normalizer', ['priority' => -889]) ->tag('kernel.reset', ['method' => '?reset']); diff --git a/src/Symfony/Bundle/Resources/config/metadata/resource.php b/src/Symfony/Bundle/Resources/config/metadata/resource.php index 137ad0515de..c576f04b2f3 100644 --- a/src/Symfony/Bundle/Resources/config/metadata/resource.php +++ b/src/Symfony/Bundle/Resources/config/metadata/resource.php @@ -29,6 +29,7 @@ use ApiPlatform\Metadata\Resource\Factory\OperationNameResourceMetadataCollectionFactory; use ApiPlatform\Metadata\Resource\Factory\ParameterResourceMetadataCollectionFactory; use ApiPlatform\Metadata\Resource\Factory\PhpFileResourceMetadataCollectionFactory; +use ApiPlatform\Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\UriTemplateResourceMetadataCollectionFactory; use ApiPlatform\Symfony\Metadata\Resource\Factory\ContainerParameterResourceMetadataCollectionFactory; @@ -163,6 +164,14 @@ service('api_platform.resource_class_resolver')->ignoreOnInvalid(), ]); + $services->set('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql', PolymorphicGraphQlResourceMetadataCollectionFactory::class) + ->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 750) + ->args([ + service('serializer.mapping.class_discriminator_resolver'), + service('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql.inner'), + '%api_platform.defaults%', + ]); + $services->set('api_platform.metadata.resource.metadata_collection_factory.cached', CachedResourceMetadataCollectionFactory::class) ->decorate('api_platform.metadata.resource.metadata_collection_factory', null, -10) ->args([ diff --git a/src/Symfony/Bundle/Resources/config/state/object_mapper.php b/src/Symfony/Bundle/Resources/config/state/object_mapper.php index ad970c8d2d2..74fcafc5750 100644 --- a/src/Symfony/Bundle/Resources/config/state/object_mapper.php +++ b/src/Symfony/Bundle/Resources/config/state/object_mapper.php @@ -15,6 +15,7 @@ use ApiPlatform\Metadata\Resource\Factory\ObjectMapperMetadataCollectionFactory; use ApiPlatform\State\ObjectMapper\ObjectMapper; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; use ApiPlatform\State\Provider\ObjectMapperProvider; use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory; @@ -25,6 +26,14 @@ $services->alias('api_platform.object_mapper', 'object_mapper'); + $services->set('api_platform.object_mapper.subtype', SubtypeObjectMapper::class) + ->decorate('api_platform.object_mapper', null, 0) + ->args([ + service('api_platform.object_mapper.subtype.inner'), + service('api_platform.serializer.subtype_resolver'), + service('api_platform.object_mapper.metadata_factory'), + ]); + $services->set('api_platform.object_mapper.relation', ObjectMapper::class) ->decorate('api_platform.object_mapper', null, -255) ->args([service('api_platform.object_mapper.relation.inner')]); @@ -42,5 +51,6 @@ ->args([ service('api_platform.metadata.resource.metadata_collection_factory.object_mapper.inner'), service('api_platform.object_mapper.metadata_factory'), + service_closure('api_platform.serializer.subtype_resolver')->ignoreOnInvalid(), ]); }; diff --git a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php index 01b34d353e3..764685ffedd 100644 --- a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php +++ b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php @@ -29,6 +29,7 @@ use ApiPlatform\Tests\Fixtures\TestBundle\TestBundle; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use Doctrine\ORM\OptimisticLockException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; @@ -677,4 +678,42 @@ public function testPurgeTagsProcessorsDecorateMongoDbOdmProcessorsWhenInvalidat $this->assertSame('api_platform.doctrine_mongodb.odm.state.remove_processor', $this->container->getDefinition('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.remove_processor')->getDecoratedService()[0]); $this->assertNotContainerHasService('api_platform.doctrine.orm.http_cache.purge_tags.persist_processor'); } + + public function testResourcePolymorphismIsDisabledByDefault(): 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->assertNotContainerHasService('api_platform.serializer.subtype_resolver'); + $this->assertNotContainerHasService('api_platform.doctrine.orm.serializer.discriminator_mapping_loader'); + $this->assertNotContainerHasService('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader'); + } + + /** + * @return iterable, ?string}> + */ + public static function resourcePolymorphismConfigProvider(): iterable + { + yield 'serializer' => [['serializer' => ['discriminator_map' => true]], null]; + yield 'doctrine' => [['doctrine' => ['enabled' => true, 'discriminator_map' => true]], 'api_platform.doctrine.orm.serializer.discriminator_mapping_loader']; + yield 'doctrine_mongodb_odm' => [['doctrine_mongodb_odm' => ['enabled' => true, 'discriminator_map' => true]], 'api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader']; + } + + /** + * @param array $polymorphismConfig + */ + #[DataProvider('resourcePolymorphismConfigProvider')] + public function testResourcePolymorphismCanBeEnabled(array $polymorphismConfig, ?string $loader): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform'] = $polymorphismConfig + $config['api_platform']; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertContainerHasService('api_platform.serializer.subtype_resolver'); + if (null !== $loader) { + $this->assertContainerHasService($loader); + } + } } diff --git a/src/Symfony/composer.json b/src/Symfony/composer.json index 57f9045c54e..399c18f1281 100644 --- a/src/Symfony/composer.json +++ b/src/Symfony/composer.json @@ -31,13 +31,13 @@ "php": ">=8.2", "api-platform/documentation": "^5.0", "api-platform/http-cache": "^5.0", - "api-platform/json-schema": "^5.0", - "api-platform/jsonld": "^5.0", - "api-platform/hydra": "^5.0", - "api-platform/metadata": "^5.0", - "api-platform/serializer": "^5.0", - "api-platform/state": "^5.0", - "api-platform/validator": "^5.0", + "api-platform/json-schema": "^5.1", + "api-platform/jsonld": "^5.1", + "api-platform/hydra": "^5.1", + "api-platform/metadata": "^5.1", + "api-platform/serializer": "^5.1", + "api-platform/state": "^5.1", + "api-platform/validator": "^5.1", "api-platform/openapi": "^5.0", "symfony/asset": "^7.4 || ^8.0", "symfony/deprecation-contracts": "^3.1", @@ -50,13 +50,13 @@ "willdurand/negotiation": "^3.1" }, "require-dev": { - "api-platform/doctrine-common": "^5.0", + "api-platform/doctrine-common": "^5.1", "api-platform/doctrine-odm": "^5.0", "api-platform/doctrine-orm": "^5.0", "api-platform/elasticsearch": "^5.0", "api-platform/graphql": "^5.0", - "api-platform/hal": "^5.0", - "api-platform/json-api": "^5.0", + "api-platform/hal": "^5.1", + "api-platform/json-api": "^5.1", "api-platform/test": "^5.0", "phpspec/prophecy-phpunit": "^2.2", "phpunit/phpunit": "^11.5 || ^12.2 || ^13.0", diff --git a/src/Validator/DenormalizationViolationFactory.php b/src/Validator/DenormalizationViolationFactory.php index a9a2c6eeebc..38af0ce4059 100644 --- a/src/Validator/DenormalizationViolationFactory.php +++ b/src/Validator/DenormalizationViolationFactory.php @@ -15,6 +15,7 @@ use ApiPlatform\Metadata\Operation; use ApiPlatform\State\DenormalizationViolationFactoryInterface; +use ApiPlatform\State\Exception\UnprocessableValueException; use ApiPlatform\Validator\Exception\ValidationException; use Symfony\Component\Serializer\Exception\NotNormalizableValueException; use Symfony\Component\Serializer\Exception\PartialDenormalizationException; @@ -108,6 +109,10 @@ public function handle(NotNormalizableValueException|PartialDenormalizationExcep */ private function buildViolation(NotNormalizableValueException $exception, Operation $operation, bool $generic = false): ?ConstraintViolationInterface { + if ($exception instanceof UnprocessableValueException) { + return $this->emitViolation($exception, null, $exception->getViolationCode()); + } + $path = $exception->getPath(); if (null === $path || '' === $path) { return $generic ? $this->emitViolation($exception, null, (string) Type::INVALID_TYPE_ERROR) : null; diff --git a/src/Validator/composer.json b/src/Validator/composer.json index 39c94a81cd1..50ad44fa9e5 100644 --- a/src/Validator/composer.json +++ b/src/Validator/composer.json @@ -24,7 +24,7 @@ "require": { "php": ">=8.2", "api-platform/metadata": "^5.0", - "api-platform/state": "^5.0", + "api-platform/state": "^5.1", "symfony/type-info": "^7.4 || ^8.0", "symfony/http-kernel": "^7.4 || ^8.0", "symfony/serializer": "^7.4 || ^8.0", diff --git a/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeCar.php b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeCar.php new file mode 100644 index 00000000000..70d0c723f8a --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeCar.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\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty; + +final class ConvertedTypeCar extends ConvertedTypeVehicle +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeTruck.php b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeTruck.php new file mode 100644 index 00000000000..1e6970e0247 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeTruck.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\ConvertedTypeProperty; + +final class ConvertedTypeTruck extends ConvertedTypeVehicle +{ + public int $payload = 0; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicle.php b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicle.php new file mode 100644 index 00000000000..910be5165c3 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicle.php @@ -0,0 +1,51 @@ + + * + * 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\ConvertedTypeProperty; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[ApiResource( + operations: [new Get(), new Post(), new Put()], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +#[DiscriminatorMap(typeProperty: 'type', mapping: [ + 'car' => ConvertedTypeCar::class, + 'truck' => ConvertedTypeTruck::class, +])] +abstract class ConvertedTypeVehicle +{ + #[ApiProperty(identifier: true, writable: false)] + public ?int $id = null; + + public string $name = ''; + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): ?self + { + return ConvertedTypeVehicleStore::$vehicles[(int) $uriVariables['id']] ?? null; + } + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): self + { + $data->id ??= (ConvertedTypeVehicleStore::$vehicles ? max(array_keys(ConvertedTypeVehicleStore::$vehicles)) : 0) + 1; + + return ConvertedTypeVehicleStore::$vehicles[$data->id] = $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicleStore.php b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicleStore.php new file mode 100644 index 00000000000..52b8f6f05e8 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/ConvertedTypeProperty/ConvertedTypeVehicleStore.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\ConvertedTypeProperty; + +final class ConvertedTypeVehicleStore +{ + /** @var array */ + public static array $vehicles = []; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/ArchiveBookAction.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/ArchiveBookAction.php new file mode 100644 index 00000000000..19f1c620c5b --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/ArchiveBookAction.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\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction; + +final class ArchiveBookAction extends BookAction +{ + public function __construct( + public readonly string $reason, + ) { + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookAction.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookAction.php new file mode 100644 index 00000000000..48e7b5e7184 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookAction.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\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: 'action', mapping: [ + 'archive' => ArchiveBookAction::class, + 'merge' => MergeBookAction::class, +])] +abstract class BookAction +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookActionResource.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookActionResource.php new file mode 100644 index 00000000000..c0d5f5e5e50 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/BookActionResource.php @@ -0,0 +1,42 @@ + + * + * 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\DiscriminatedBookAction; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; + +#[ApiResource( + operations: [ + new Post( + uriTemplate: '/discriminated_book_actions', + input: BookAction::class, + processor: [self::class, 'process'], + ), + ] +)] +final class BookActionResource +{ + public ?int $id = 1; + + public ?string $performed = null; + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): self + { + $resource = new self(); + $resource->performed = $data::class; + + return $resource; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/MergeBookAction.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/MergeBookAction.php new file mode 100644 index 00000000000..7bc3e586471 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedBookAction/MergeBookAction.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\ApiResource\DiscriminatedBookAction; + +final class MergeBookAction extends BookAction +{ + /** + * @param list $sources + */ + public function __construct( + public readonly string $target, + public readonly array $sources = [], + ) { + } +} 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/DiscriminatedBus.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedBus.php new file mode 100644 index 00000000000..5d6d8cc5dc9 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedBus.php @@ -0,0 +1,30 @@ + + * + * 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\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Put; + +#[ApiResource( + operations: [new Get(), new Put(), new Patch()], + types: ['https://schema.org/BusOrCoach'], + provider: [DiscriminatedVehicle::class, 'provide'], + processor: [DiscriminatedVehicle::class, 'process'], +)] +final class DiscriminatedBus extends DiscriminatedVehicle +{ + public int $seats = 0; +} 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..8da81e772e7 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicle.php @@ -0,0 +1,100 @@ + + * + * 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(), + ], + types: ['https://schema.org/Vehicle'], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +#[DiscriminatorMap(typeProperty: 'kind', mapping: [ + 'car' => DiscriminatedCar::class, + 'truck' => DiscriminatedTruck::class, + 'bike' => DiscriminatedBike::class, + 'bus' => DiscriminatedBus::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/ApiResource/GarageWithPolymorphicVehicle/Garage.php b/tests/Fixtures/TestBundle/ApiResource/GarageWithPolymorphicVehicle/Garage.php new file mode 100644 index 00000000000..6d579137079 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/GarageWithPolymorphicVehicle/Garage.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\ApiResource\GarageWithPolymorphicVehicle; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedVehicle; + +#[ApiResource(provider: [self::class, 'provide'])] +class Garage +{ + #[ApiProperty(identifier: true)] + public ?int $id = null; + + public ?DiscriminatedVehicle $vehicle = null; + + /** @var DiscriminatedVehicle[] */ + public array $vehicles = []; + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): self + { + $car = new DiscriminatedCar(); + $car->id = 1; + $car->name = 'Beetle'; + + $garage = new self(); + $garage->id = 1; + $garage->vehicle = $car; + $garage->vehicles = [$car]; + + return $garage; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php new file mode 100644 index 00000000000..3c4ac4c69f3 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.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\MappedDiscriminatedVehicle; + +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: DoctrineDiscriminatedCar::class)] +#[Map(target: DoctrineDiscriminatedCar::class)] +final class MappedCar extends MappedVehicle +{ + public int $seats = 4; + public ?string $vin = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php new file mode 100644 index 00000000000..97e30117fb1 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.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\Tests\Fixtures\TestBundle\ApiResource\MappedDiscriminatedVehicle; + +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: DoctrineDiscriminatedTruck::class)] +#[Map(target: DoctrineDiscriminatedTruck::class)] +final class MappedTruck extends MappedVehicle +{ + public int $payload = 0; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php new file mode 100644 index 00000000000..535520cba68 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.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\ApiResource\MappedDiscriminatedVehicle; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[ApiResource( + shortName: 'MappedVehicle', + operations: [new Get(), new GetCollection(), new Post()], + stateOptions: new Options(entityClass: DoctrineDiscriminatedVehicle::class), +)] +#[DiscriminatorMap(typeProperty: 'kind', mapping: ['car' => MappedCar::class, 'truck' => MappedTruck::class])] +abstract class MappedVehicle +{ + public ?int $id = null; + public string $name = ''; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeCar.php b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeCar.php new file mode 100644 index 00000000000..acb7e9934f2 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeCar.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\SharedTypeIri; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; + +#[ApiResource( + operations: [new Get()], + types: ['https://schema.org/Vehicle'], + provider: [SharedTypeVehicle::class, 'provide'], + processor: [SharedTypeVehicle::class, 'process'], +)] +final class SharedTypeCar extends SharedTypeVehicle +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeTruck.php b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeTruck.php new file mode 100644 index 00000000000..70cc2c9c16b --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeTruck.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\SharedTypeIri; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; + +#[ApiResource( + operations: [new Get()], + types: ['https://schema.org/Vehicle'], + provider: [SharedTypeVehicle::class, 'provide'], + processor: [SharedTypeVehicle::class, 'process'], +)] +final class SharedTypeTruck extends SharedTypeVehicle +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicle.php b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicle.php new file mode 100644 index 00000000000..35ce3d4af91 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicle.php @@ -0,0 +1,51 @@ + + * + * 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\SharedTypeIri; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[ApiResource( + operations: [new Get(), new Post()], + types: ['https://schema.org/Vehicle'], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +#[DiscriminatorMap(typeProperty: 'kind', mapping: [ + 'car' => SharedTypeCar::class, + 'truck' => SharedTypeTruck::class, +])] +abstract class SharedTypeVehicle +{ + #[ApiProperty(identifier: true, writable: false)] + public ?int $id = null; + + public string $name = ''; + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): ?self + { + return SharedTypeVehicleStore::$vehicles[(int) $uriVariables['id']] ?? null; + } + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): self + { + $data->id ??= (SharedTypeVehicleStore::$vehicles ? max(array_keys(SharedTypeVehicleStore::$vehicles)) : 0) + 1; + + return SharedTypeVehicleStore::$vehicles[$data->id] = $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicleStore.php b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicleStore.php new file mode 100644 index 00000000000..85b958f35f8 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/SharedTypeIri/SharedTypeVehicleStore.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\SharedTypeIri; + +final class SharedTypeVehicleStore +{ + /** @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..ce1595dc298 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCar.php @@ -0,0 +1,38 @@ + + * + * 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 ApiPlatform\Metadata\Put; +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(), new Put()])] +#[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/Functional/ConvertedTypePropertyTest.php b/tests/Functional/ConvertedTypePropertyTest.php new file mode 100644 index 00000000000..f230c67ea3b --- /dev/null +++ b/tests/Functional/ConvertedTypePropertyTest.php @@ -0,0 +1,82 @@ + + * + * 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\ConvertedTypeProperty\ConvertedTypeTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty\ConvertedTypeVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty\ConvertedTypeVehicleStore; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class ConvertedTypePropertyTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [ConvertedTypeVehicle::class]; + } + + protected function tearDown(): void + { + ConvertedTypeVehicleStore::$vehicles = []; + + parent::tearDown(); + } + + public function testJsonApiReadsTheNameConvertedTypeProperty(): void + { + $truck = new ConvertedTypeTruck(); + $truck->id = 1; + $truck->name = 'Actros'; + ConvertedTypeVehicleStore::$vehicles[1] = $truck; + + $attributes = self::createClient()->request('GET', '/converted_type_vehicles/1', ['headers' => ['Accept' => 'application/vnd.api+json']])->toArray()['data']['attributes']; + $this->assertSame('truck', $attributes['_type']); + + self::createClient()->request('POST', '/converted_type_vehicles', [ + 'headers' => ['Content-Type' => 'application/vnd.api+json', 'Accept' => 'application/vnd.api+json'], + 'json' => ['data' => ['type' => 'ConvertedTypeVehicle', 'attributes' => ['_type' => 'truck', 'name' => 'Arocs', 'payload' => 7500]]], + ]); + + $this->assertResponseStatusCodeSame(201); + $this->assertSame(ConvertedTypeTruck::class, ConvertedTypeVehicleStore::$vehicles[2]::class); + } + + public function testJsonApiRejectsAChangeOfTheNameConvertedTypeProperty(): void + { + $truck = new ConvertedTypeTruck(); + $truck->id = 1; + $truck->name = 'Actros'; + ConvertedTypeVehicleStore::$vehicles[1] = $truck; + + self::createClient()->request('PUT', '/converted_type_vehicles/1', [ + 'headers' => ['Content-Type' => 'application/vnd.api+json', 'Accept' => 'application/vnd.api+json'], + 'json' => ['data' => ['type' => 'ConvertedTypeVehicle', 'attributes' => ['_type' => 'car', 'name' => 'Golf']]], + ]); + + $this->assertResponseStatusCodeSame(422); + $this->assertSame('Actros', ConvertedTypeVehicleStore::$vehicles[1]->name); + } +} diff --git a/tests/Functional/DiscriminatedResourceGraphQlTest.php b/tests/Functional/DiscriminatedResourceGraphQlTest.php new file mode 100644 index 00000000000..760e42479eb --- /dev/null +++ b/tests/Functional/DiscriminatedResourceGraphQlTest.php @@ -0,0 +1,73 @@ + + * + * 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\DiscriminatedBus; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\GarageWithPolymorphicVehicle\Garage; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\GraphQlInputDefaultTags; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class DiscriminatedResourceGraphQlTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [DiscriminatedVehicle::class, DiscriminatedBus::class, GraphQlInputDefaultTags::class, Garage::class]; + } + + public function testPolymorphicResourcesAreNotExposedInTheSchema(): void + { + $response = self::createClient()->request('POST', '/graphql', ['json' => [ + 'query' => '{ __schema { queryType { fields { name } } mutationType { fields { name } } } }', + ]]); + + $this->assertResponseIsSuccessful(); + $json = $response->toArray(false); + $this->assertArrayNotHasKey('errors', $json, json_encode($json['errors'] ?? null)); + + $fields = array_map(static fn (array $field): string => $field['name'], [...$json['data']['__schema']['queryType']['fields'], ...$json['data']['__schema']['mutationType']['fields']]); + $this->assertContains('graphQlInputDefaultTags', $fields); + foreach ($fields as $field) { + $this->assertStringNotContainsStringIgnoringCase('discriminated', $field); + } + } + + public function testRelationToAPolymorphicResourceKeepsTheSchemaValid(): void + { + $response = self::createClient()->request('POST', '/graphql', ['json' => [ + 'query' => '{ __type(name: "Garage") { fields { name type { name kind } } } garage(id: "/garages/1") { id vehicle { name } } }', + ]]); + + $this->assertResponseIsSuccessful(); + $json = $response->toArray(false); + $this->assertArrayNotHasKey('errors', $json, json_encode($json['errors'] ?? null)); + $this->assertSame(['id', '_id', 'vehicle', 'vehicles'], array_column($json['data']['__type']['fields'], 'name')); + $this->assertSame('DiscriminatedVehicle', $json['data']['__type']['fields'][2]['type']['name']); + $this->assertSame('DiscriminatedVehicleCursorConnection', $json['data']['__type']['fields'][3]['type']['name']); + $this->assertSame('Beetle', $json['data']['garage']['vehicle']['name']); + } +} diff --git a/tests/Functional/DiscriminatedResourceTest.php b/tests/Functional/DiscriminatedResourceTest.php new file mode 100644 index 00000000000..c5a1c704972 --- /dev/null +++ b/tests/Functional/DiscriminatedResourceTest.php @@ -0,0 +1,401 @@ + + * + * 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\State\Exception\UnprocessableValueException; +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedBike; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedBus; +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; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [DiscriminatedVehicle::class, DiscriminatedBus::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, string}> + */ + public static function postProvider(): iterable + { + yield 'subtype' => [['kind' => 'truck', 'name' => 'Scania', 'payload' => 12000], DiscriminatedTruck::class, 'DiscriminatedTruck']; + yield 'nested subtype' => [['kind' => 'bike', 'frame' => 'mountain', 'name' => 'Trek', 'suspension' => 'hardtail'], DiscriminatedMountainBike::class, 'DiscriminatedMountainBike']; + yield 'class declared in its own nested map' => [['kind' => 'bike', 'frame' => 'bike', 'name' => 'Brompton', 'gears' => 3], DiscriminatedBike::class, 'DiscriminatedBike']; + } + + /** + * @param array $payload + * @param class-string $class + */ + #[DataProvider('postProvider')] + public function testPostCreatesTheMostSpecificSubtype(array $payload, string $class, string $type): 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' => $type] + $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']]; + } + + /** + * @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, 4?: 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']; + yield 'type change on PATCH' => ['PATCH', '/discriminated_vehicles/1', ['kind' => 'truck', 'payload' => 1], 'kind', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield 'nested type change on PATCH' => ['PATCH', '/discriminated_vehicles/4', ['frame' => 'bike'], 'frame', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield 'type change on PUT' => ['PUT', '/discriminated_vehicles/1', ['kind' => 'truck', 'name' => 'Unimog', 'payload' => 5000], 'kind', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield 'nested type change on PUT' => ['PUT', '/discriminated_vehicles/4', ['kind' => 'bike', 'frame' => 'bike', 'name' => 'Rocky'], 'frame', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield '@type contradicting the type' => ['POST', '/discriminated_vehicles', ['@type' => 'DiscriminatedCar', 'kind' => 'truck', 'name' => 'Scania'], 'kind', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield '@type of a resource subtype contradicting the type' => ['POST', '/discriminated_vehicles', ['@type' => 'https://schema.org/BusOrCoach', 'kind' => 'truck', 'name' => 'Scania'], 'kind', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + yield '@type contradicting the nested type' => ['POST', '/discriminated_vehicles', ['@type' => 'DiscriminatedMountainBike', 'kind' => 'bike', 'frame' => 'bike', 'name' => 'Brompton'], 'frame', UnprocessableValueException::TYPE_MISMATCH_ERROR]; + } + + /** + * @param array $payload + */ + #[DataProvider('constraintViolationProvider')] + public function testSubtypeConstraintsAreValidated(string $method, string $uri, array $payload, string $propertyPath, ?string $code = null): 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(422); + $this->assertJsonContains(['violations' => [['propertyPath' => $propertyPath] + (null === $code ? [] : ['code' => $code])]]); + $this->assertSame($classes, array_map(static fn (DiscriminatedVehicle $vehicle): string => $vehicle::class, DiscriminatedVehicleStore::$vehicles)); + } + + 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]); + } + + /** + * @return iterable}> + */ + public static function leafResourceTypeChangeProvider(): iterable + { + yield 'PATCH on the endpoint of the leaf resource' => ['PATCH', '/discriminated_buses/6', ['kind' => 'car']]; + yield 'PATCH of a leaf resource on the root endpoint' => ['PATCH', '/discriminated_vehicles/6', ['kind' => 'car']]; + yield 'PUT to a leaf resource on the root endpoint' => ['PUT', '/discriminated_vehicles/1', ['kind' => 'bus', 'name' => 'Citaro']]; + } + + /** + * @param array $payload + */ + #[DataProvider('leafResourceTypeChangeProvider')] + public function testLeafResourceTypeCannotChange(string $method, string $uri, array $payload): void + { + $bus = new DiscriminatedBus(); + $bus->id = 6; + $bus->name = 'Citaro'; + DiscriminatedVehicleStore::$vehicles[6] = $bus; + + 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' => 'kind', 'code' => UnprocessableValueException::TYPE_MISMATCH_ERROR]]]); + $this->assertInstanceOf(DiscriminatedCar::class, DiscriminatedVehicleStore::$vehicles[1]); + $this->assertInstanceOf(DiscriminatedBus::class, DiscriminatedVehicleStore::$vehicles[6]); + } + + public function testPutKeepingTheSubtypeReplacesTheResource(): void + { + self::createClient()->request('PUT', '/discriminated_vehicles/2', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Unimog', 'payload' => 5000], + ]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains(['@id' => '/discriminated_vehicles/2', 'kind' => 'truck', 'name' => 'Unimog', 'payload' => 5000]); + $this->assertInstanceOf(DiscriminatedTruck::class, DiscriminatedVehicleStore::$vehicles[2]); + } + + 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/DiscriminatedCar.jsonld', + 'truck' => '#/components/schemas/DiscriminatedTruck.jsonld', + 'bike' => '#/components/schemas/DiscriminatedBike.jsonld', + 'bus' => '#/components/schemas/DiscriminatedBus.jsonld', + ], + ], $output['discriminator']); + $this->assertCount(4, $output['oneOf']); + $this->assertArrayNotHasKey('properties', $output); + + $truck = $schemas['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['DiscriminatedCar.jsonld']['properties']['name']); + + // The nested map lists the bike itself: an instance of the bike is described by an inline branch + $bike = $schemas['DiscriminatedBike.jsonld']; + $this->assertSame('frame', $bike['discriminator']['propertyName']); + $this->assertSame(['type' => 'string', 'enum' => ['bike']], $bike['oneOf'][0]['properties']['frame']); + $this->assertSame(['$ref' => '#/components/schemas/DiscriminatedMountainBike.jsonld'], $bike['oneOf'][1]); + + // Unmapped subclasses are never documented + $this->assertArrayNotHasKey('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->assertContains('#DiscriminatedVehicle/kind', array_column(array_column($classes['#DiscriminatedVehicle']['hydra:supportedProperty'], 'hydra:property'), '@id')); + $this->assertContains('#DiscriminatedBike/frame', array_column(array_column($classes['#DiscriminatedBike']['hydra:supportedProperty'], 'hydra:property'), '@id')); + $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']); + $this->assertSame('DiscriminatedVehicle/kind', $context['kind']); + $this->assertSame('DiscriminatedBike/frame', $context['frame']); + } +} diff --git a/tests/Functional/DiscriminatedResourceWithoutPolymorphismTest.php b/tests/Functional/DiscriminatedResourceWithoutPolymorphismTest.php new file mode 100644 index 00000000000..2d1b57df5e6 --- /dev/null +++ b/tests/Functional/DiscriminatedResourceWithoutPolymorphismTest.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\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty\ConvertedTypeTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty\ConvertedTypeVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ConvertedTypeProperty\ConvertedTypeVehicleStore; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeCar; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeVehicleStore; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class DiscriminatedResourceWithoutPolymorphismTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [ConvertedTypeVehicle::class, SharedTypeVehicle::class, SharedTypeCar::class]; + } + + protected function tearDown(): void + { + ConvertedTypeVehicleStore::$vehicles = []; + SharedTypeVehicleStore::$vehicles = []; + + parent::tearDown(); + } + + public function testPutWithoutTheTypePropertyDoesNotKeepTheStoredClass(): void + { + $truck = new ConvertedTypeTruck(); + $truck->id = 1; + $truck->name = 'Actros'; + ConvertedTypeVehicleStore::$vehicles[1] = $truck; + + self::createClient()->request('PUT', '/converted_type_vehicles/1', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['name' => 'Arocs'], + ]); + + $this->assertResponseStatusCodeSame(400); + $this->assertSame('Actros', ConvertedTypeVehicleStore::$vehicles[1]->name); + } + + public function testOpenApiDoesNotDocumentTheSubtypesOfAResource(): void + { + $schemas = self::createClient()->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray()['components']['schemas']; + + $schema = $schemas['ConvertedTypeVehicle'] ?? $schemas['ConvertedTypeVehicle.jsonld'] ?? []; + $this->assertNotSame([], $schema); + $this->assertArrayNotHasKey('oneOf', $schema); + $this->assertArrayNotHasKey('discriminator', $schema); + } + + public function testGetDoesNotEmitTheTypeProperty(): void + { + $truck = new ConvertedTypeTruck(); + $truck->id = 1; + $truck->name = 'Actros'; + ConvertedTypeVehicleStore::$vehicles[1] = $truck; + + $json = self::createClient()->request('GET', '/converted_type_vehicles/1')->toArray(); + + $this->assertArrayNotHasKey('type', $json); + } + + public function testSubtypeResourceDoesNotDocumentNorEmitTheTypeProperty(): void + { + $car = new SharedTypeCar(); + $car->id = 1; + $car->name = 'Golf'; + SharedTypeVehicleStore::$vehicles[1] = $car; + + $client = self::createClient(); + $this->assertArrayNotHasKey('kind', $client->request('GET', '/shared_type_cars/1')->toArray()); + + $schemas = $client->request('GET', '/docs', ['headers' => ['Accept' => 'application/vnd.openapi+json']])->toArray()['components']['schemas']; + $this->assertArrayNotHasKey('kind', $schemas['SharedTypeCar']['properties']); + } +} diff --git a/tests/Functional/DiscriminatorMapAppKernel.php b/tests/Functional/DiscriminatorMapAppKernel.php new file mode 100644 index 00000000000..8c624289649 --- /dev/null +++ b/tests/Functional/DiscriminatorMapAppKernel.php @@ -0,0 +1,42 @@ + + * + * 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) resource polymorphism through serializer discriminator maps. + */ +class DiscriminatorMapAppKernel extends \AppKernel +{ + public function getCacheDir(): string + { + return parent::getCacheDir().'/discriminator_map'; + } + + public function getLogDir(): string + { + return parent::getLogDir().'/discriminator_map'; + } + + protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader): void + { + parent::configureContainer($c, $loader); + + $loader->load(static function (ContainerBuilder $container): void { + $container->loadFromExtension('api_platform', ['serializer' => ['discriminator_map' => true]]); + }); + } +} diff --git a/tests/Functional/DiscriminatorMapOpenApiTest.php b/tests/Functional/DiscriminatorMapOpenApiTest.php new file mode 100644 index 00000000000..9a31e737d29 --- /dev/null +++ b/tests/Functional/DiscriminatorMapOpenApiTest.php @@ -0,0 +1,96 @@ + + * + * 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\DiscriminatedBookAction\BookAction; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction\BookActionResource; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction\MergeBookAction; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class DiscriminatorMapOpenApiTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [BookActionResource::class]; + } + + public function testDiscriminatedInputIsDocumentedAsOneOf(): void + { + $response = self::createClient()->request('GET', '/docs', [ + 'headers' => ['Accept' => 'application/vnd.openapi+json'], + ]); + $this->assertResponseIsSuccessful(); + + $json = $response->toArray(); + $schemas = $json['components']['schemas']; + + $requestSchema = $json['paths']['/discriminated_book_actions']['post']['requestBody']['content']['application/ld+json']['schema']; + $this->assertSame(['$ref' => '#/components/schemas/BookActionResource.BookAction'], $requestSchema); + + $this->assertSame([ + 'oneOf' => [ + ['$ref' => '#/components/schemas/ArchiveBookAction'], + ['$ref' => '#/components/schemas/MergeBookAction'], + ], + 'discriminator' => [ + 'propertyName' => 'action', + 'mapping' => [ + 'archive' => '#/components/schemas/ArchiveBookAction', + 'merge' => '#/components/schemas/MergeBookAction', + ], + ], + ], $schemas['BookActionResource.BookAction']); + + $archive = $schemas['ArchiveBookAction']; + $this->assertSame(['type' => 'string', 'enum' => ['archive']], $archive['properties']['action']); + $this->assertSame(['type' => 'string'], $archive['properties']['reason']); + $this->assertSame(['action'], $archive['required']); + + $merge = $schemas['MergeBookAction']; + $this->assertSame(['type' => 'string', 'enum' => ['merge']], $merge['properties']['action']); + $this->assertArrayHasKey('sources', $merge['properties']); + $this->assertSame(['action'], $merge['required']); + } + + public function testDiscriminatorIsOpenApiOnly(): void + { + $schema = self::getContainer()->get('api_platform.json_schema.schema_factory')->buildSchema(BookAction::class, 'json', 'input'); + $definition = $schema->getDefinitions()['BookAction']; + + $this->assertSame([ + ['$ref' => '#/definitions/ArchiveBookAction'], + ['$ref' => '#/definitions/MergeBookAction'], + ], $definition['oneOf']); + $this->assertArrayNotHasKey('discriminator', $definition); + } + + public function testDiscriminatedInputIsDenormalized(): void + { + self::createClient()->request('POST', '/discriminated_book_actions', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['action' => 'merge', 'target' => '/books/1', 'sources' => ['/books/2']], + ]); + + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['performed' => MergeBookAction::class]); + } +} 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..33cedc8e153 --- /dev/null +++ b/tests/Functional/DoctrineDiscriminatedResourceTest.php @@ -0,0 +1,231 @@ + + * + * 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 testPostToAConcreteSubtypeEndpointDoesNotRequireTheTypeProperty(): void + { + self::createClient()->request('POST', '/doctrine_discriminated_cars', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['name' => 'City car', 'seats' => 3], + ]); + + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['@id' => '/doctrine_discriminated_cars/4', '@type' => 'DoctrineDiscriminatedCar', 'kind' => 'car', 'seats' => 3]); + $this->assertSame(DoctrineDiscriminatedCar::class, $this->findVehicle(4)::class); + } + + public function testPutWithoutTheTypePropertyKeepsTheSubtype(): void + { + self::createClient()->request('PUT', '/doctrine_discriminated_cars/3', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['name' => 'Renamed', 'seats' => 4], + ]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains(['@id' => '/doctrine_discriminated_cars/3', '@type' => 'DoctrineDiscriminatedSportsCar', 'kind' => 'sportsCar', 'name' => 'Renamed']); + $this->assertSame(DoctrineDiscriminatedSportsCar::class, $this->findVehicle(3)::class); + } + + 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/Functional/JsonLd/SharedTypeIriTest.php b/tests/Functional/JsonLd/SharedTypeIriTest.php new file mode 100644 index 00000000000..ca80b608a8a --- /dev/null +++ b/tests/Functional/JsonLd/SharedTypeIriTest.php @@ -0,0 +1,74 @@ + + * + * 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\JsonLd; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeCar; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\SharedTypeIri\SharedTypeVehicleStore; +use ApiPlatform\Tests\Functional\DiscriminatorMapAppKernel; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use PHPUnit\Framework\Attributes\DataProvider; + +final class SharedTypeIriTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [SharedTypeVehicle::class, SharedTypeCar::class, SharedTypeTruck::class]; + } + + protected function tearDown(): void + { + SharedTypeVehicleStore::$vehicles = []; + + parent::tearDown(); + } + + /** + * @return iterable + */ + public static function kindProvider(): iterable + { + yield 'car' => ['car', SharedTypeCar::class]; + yield 'truck' => ['truck', SharedTypeTruck::class]; + } + + /** + * @param class-string $class + */ + #[DataProvider('kindProvider')] + public function testTypeSharedByTheSubtypesDoesNotContradictAnyOfThem(string $kind, string $class): void + { + self::createClient()->request('POST', '/shared_type_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['@type' => 'https://schema.org/Vehicle', 'kind' => $kind, 'name' => 'Shared'], + ]); + + $this->assertResponseStatusCodeSame(201); + $this->assertSame($class, SharedTypeVehicleStore::$vehicles[1]::class); + } +} diff --git a/tests/Functional/MappedDiscriminatedResourceTest.php b/tests/Functional/MappedDiscriminatedResourceTest.php new file mode 100644 index 00000000000..dc2e09a1335 --- /dev/null +++ b/tests/Functional/MappedDiscriminatedResourceTest.php @@ -0,0 +1,110 @@ + + * + * 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\MappedDiscriminatedVehicle\MappedVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedSportsCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class MappedDiscriminatedResourceTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + public static function getResources(): array + { + return [MappedVehicle::class]; + } + + protected function setUp(): void + { + if ($this->isMongoDB()) { + $this->markTestSkipped('ORM only.'); + } + + $this->recreateSchema([DoctrineDiscriminatedVehicle::class, DoctrineDiscriminatedCar::class, DoctrineDiscriminatedSportsCar::class, DoctrineDiscriminatedTruck::class]); + } + + public function testGetItemMapsEntitySubtypeToResourceSubtype(): void + { + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Volvo'; + $truck->payload = 20000; + $this->persist($truck); + + self::createClient()->request('GET', '/mapped_vehicles/'.$truck->id); + + $this->assertResponseStatusCodeSame(200); + $this->assertJsonContains(['kind' => 'truck', 'name' => 'Volvo', 'payload' => 20000]); + } + + public function testGetCollectionMapsEachItemToItsSubtype(): void + { + $car = new DoctrineDiscriminatedCar(); + $car->name = 'Clio'; + $car->seats = 5; + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Volvo'; + $truck->payload = 20000; + $this->persist($car, $truck); + + self::createClient()->request('GET', '/mapped_vehicles'); + + $this->assertResponseStatusCodeSame(200); + $this->assertJsonContains([ + 'hydra:member' => [ + ['kind' => 'car', 'name' => 'Clio', 'seats' => 5], + ['kind' => 'truck', 'name' => 'Volvo', 'payload' => 20000], + ], + ]); + } + + public function testPostPersistsEntitySubtype(): void + { + self::createClient()->request('POST', '/mapped_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Scania', 'payload' => 3500], + ]); + + $this->assertResponseStatusCodeSame(201); + + $manager = $this->getManager(); + $manager->clear(); + $stored = $manager->getRepository(DoctrineDiscriminatedVehicle::class)->findOneBy(['name' => 'Scania']); + $this->assertInstanceOf(DoctrineDiscriminatedTruck::class, $stored); + $this->assertSame(3500, $stored->payload); + } + + private function persist(object ...$entities): void + { + $manager = $this->getManager(); + foreach ($entities as $entity) { + $manager->persist($entity); + } + $manager->flush(); + $manager->clear(); + } +} diff --git a/tests/JsonLd/ContextBuilderTest.php b/tests/JsonLd/ContextBuilderTest.php index 93427ff582a..a9cfa15eff6 100644 --- a/tests/JsonLd/ContextBuilderTest.php +++ b/tests/JsonLd/ContextBuilderTest.php @@ -16,6 +16,7 @@ use ApiPlatform\JsonLd\ContextBuilder; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Exception\RuntimeException; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\IriConverterInterface; use ApiPlatform\Metadata\Operations; @@ -26,6 +27,7 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; use ApiPlatform\Metadata\Resource\ResourceNameCollection; +use ApiPlatform\Metadata\SubtypeResolver; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Tests\Fixtures\TestBundle\Dto\OutputDto; use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Dummy; @@ -33,6 +35,8 @@ use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; use Prophecy\Prophecy\ObjectProphecy; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\TypeInfo\Type; /** @@ -264,4 +268,72 @@ public function testResourceContextWithoutHydraPrefix(): void $this->assertEquals($expected, $contextBuilder->getResourceContext($this->entityClass)); } + + public function testSiblingSubtypesShareTheTermOfAProperty(): void + { + $context = $this->createSubtypeContextBuilder()->getResourceContext(ContextDiscriminatedVehicle::class); + + $this->assertSame('Vehicle/seats', $context['seats']); + $this->assertSame('Vehicle/kind', $context['kind']); + } + + public function testSiblingSubtypesWithContradictoryIrisThrow(): void + { + $contextBuilder = $this->createSubtypeContextBuilder([ContextDiscriminatedCar::class => ['https://schema.org/seatingCapacity'], ContextDiscriminatedBus::class => ['https://schema.org/numberOfSeats']]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(\sprintf('The subtypes "%s" and "%s" of the resource "%s" give the "seats" property different "iris"', ContextDiscriminatedCar::class, ContextDiscriminatedBus::class, ContextDiscriminatedVehicle::class)); + + $contextBuilder->getResourceContext(ContextDiscriminatedVehicle::class); + } + + public function testSiblingSubtypesWithDifferentTermDefinitionsThrow(): void + { + $contextBuilder = $this->createSubtypeContextBuilder(seatsJsonldContext: [ContextDiscriminatedBus::class => ['@type' => 'xsd:integer']]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(\sprintf('The subtypes "%s" and "%s" of the resource "%s" define the "seats" property differently in JSON-LD', ContextDiscriminatedCar::class, ContextDiscriminatedBus::class, ContextDiscriminatedVehicle::class)); + + $contextBuilder->getResourceContext(ContextDiscriminatedVehicle::class); + } + + /** + * @param array> $seatsIris + * @param array> $seatsJsonldContext + */ + private function createSubtypeContextBuilder(array $seatsIris = [], array $seatsJsonldContext = []): ContextBuilder + { + $resourceNameCollectionFactory = $this->createStub(ResourceNameCollectionFactoryInterface::class); + $resourceNameCollectionFactory->method('create')->willReturn(new ResourceNameCollection([ContextDiscriminatedVehicle::class])); + + $resourceMetadataCollectionFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $resourceMetadataCollectionFactory->method('create')->willReturn(new ResourceMetadataCollection(ContextDiscriminatedVehicle::class, [ + (new ApiResource())->withShortName('Vehicle')->withOperations(new Operations(['get' => (new Get())->withShortName('Vehicle')])), + ])); + + $propertyNames = [ContextDiscriminatedVehicle::class => ['name'], ContextDiscriminatedCar::class => ['name', 'seats'], ContextDiscriminatedBus::class => ['name', 'seats']]; + $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')->willReturnCallback(static fn (string $class, string $property): ApiProperty => new ApiProperty(readable: true, nativeType: Type::string(), iris: 'seats' === $property ? $seatsIris[$class] ?? null : null, jsonldContext: 'seats' === $property ? $seatsJsonldContext[$class] ?? null : null)); + + $mapping = new ClassDiscriminatorMapping('kind', ['car' => ContextDiscriminatedCar::class, 'bus' => ContextDiscriminatedBus::class]); + $classDiscriminatorResolver = $this->createStub(ClassDiscriminatorResolverInterface::class); + $classDiscriminatorResolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => ContextDiscriminatedVehicle::class === $class ? $mapping : null); + + return new ContextBuilder($resourceNameCollectionFactory, $resourceMetadataCollectionFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, $this->createStub(UrlGeneratorInterface::class), subtypeResolver: new SubtypeResolver($classDiscriminatorResolver, $resourceNameCollectionFactory, $resourceMetadataCollectionFactory)); + } +} + +class ContextDiscriminatedVehicle +{ +} + +class ContextDiscriminatedCar extends ContextDiscriminatedVehicle +{ +} + +class ContextDiscriminatedBus extends ContextDiscriminatedVehicle +{ } 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' => [