diff --git a/CHANGELOG.md b/CHANGELOG.md index cdd9cfb063a..22236409a4c 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 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`. 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/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/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/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 996f3218b3f..7e6bab36f1c 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -724,7 +724,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(IriConverterInterface::class), $app->make(NameConverterInterface::class), - $defaultContext + $defaultContext, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -756,6 +757,7 @@ public function register(): void // $app->make(TagCollectorInterface::class) null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -778,6 +780,7 @@ public function register(): void $defaultContext, null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -826,6 +829,7 @@ public function register(): void $app->make(ResourceMetadataCollectionFactoryInterface::class), $app->make(ResourceAccessCheckerInterface::class), // $app->make(TagCollectorInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1024,7 +1028,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(NameConverterInterface::class), $defaultContext, - $entrypointEnabled + $entrypointEnabled, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1119,6 +1124,7 @@ public function register(): void operationResourceResolver: $app->make(OperationResourceClassResolverInterface::class), identifiersExtractor: $app->make(IdentifiersExtractorInterface::class), useIriAsId: $useIriAsId, + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1138,6 +1144,7 @@ public function register(): void $defaultContext, $app->make(ResourceMetadataCollectionFactoryInterface::class), $app->make(ResourceAccessCheckerInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1241,6 +1248,7 @@ public function register(): void null, null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1261,6 +1269,7 @@ public function register(): void $app->make(ResourceAccessCheckerInterface::class), null, $app->make(OperationResourceClassResolverInterface::class), + subtypeResolver: self::getSubtypeResolver($app), ); }); @@ -1701,4 +1710,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/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/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/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/Resources/config/api.php b/src/Symfony/Bundle/Resources/config/api.php index 0816bb1d216..5dd58eba4f0 100644 --- a/src/Symfony/Bundle/Resources/config/api.php +++ b/src/Symfony/Bundle/Resources/config/api.php @@ -184,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']); @@ -203,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/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/jsonapi.php b/src/Symfony/Bundle/Resources/config/jsonapi.php index 0b2d4b1c760..1b14fe5c063 100644 --- a/src/Symfony/Bundle/Resources/config/jsonapi.php +++ b/src/Symfony/Bundle/Resources/config/jsonapi.php @@ -84,6 +84,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 +103,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/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/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/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/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/DiscriminatedResourceTest.php b/tests/Functional/DiscriminatedResourceTest.php new file mode 100644 index 00000000000..6e870e0398a --- /dev/null +++ b/tests/Functional/DiscriminatedResourceTest.php @@ -0,0 +1,360 @@ + + * + * 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); + } + + /** + * @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); + } + } + + /** + * 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]); + } + + /** + * @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 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..c51ddcfeea1 --- /dev/null +++ b/tests/Functional/DiscriminatedResourceWithoutPolymorphismTest.php @@ -0,0 +1,88 @@ + + * + * 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 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/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/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 +{ }