From 67ad462857f09e4e31e834ed8c1b5a4f0150adbb Mon Sep 17 00:00:00 2001 From: soyuka Date: Thu, 26 Nov 2026 18:04:43 +0100 Subject: [PATCH] feat(state): map abstract targets to subtypes Resolve an abstract object mapper target to the subtype whose mapping accepts the source, so a mapped polymorphic resource can be written and read through the object mapper. --- src/Laravel/ApiPlatformProvider.php | 12 +- .../ObjectMapperMetadataCollectionFactory.php | 31 ++- .../ObjectMapper/SubtypeObjectMapper.php | 194 ++++++++++++++++++ .../ObjectMapper/AbstractMappedTarget.php | 18 ++ .../ObjectMapper/AmbiguousWriteSource.php | 22 ++ .../Tests/Fixtures/ObjectMapper/CarSource.php | 18 ++ .../ObjectMapper/ConditionalWriteSource.php | 22 ++ .../ObjectMapper/DenyingCondition.php | 22 ++ .../ObjectMapper/FirstConcreteTarget.php | 18 ++ .../ObjectMapper/InterfaceAndParentSource.php | 18 ++ .../Fixtures/ObjectMapper/ParentSource.php | 18 ++ .../Fixtures/ObjectMapper/ReadableSource.php | 18 ++ .../ObjectMapper/SecondConcreteTarget.php | 18 ++ .../ObjectMapper/ServiceConditionSource.php | 21 ++ .../Fixtures/ObjectMapper/SportsCarSource.php | 18 ++ .../ObjectMapper/TargetDeniedFromCar.php | 21 ++ .../ObjectMapper/TargetMappedFromCar.php | 21 ++ .../TargetMappedFromInterface.php | 21 ++ .../ObjectMapper/TargetMappedFromParent.php | 21 ++ .../ObjectMapper/TargetMappedFromVehicle.php | 21 ++ .../Fixtures/ObjectMapper/UnmappedSource.php | 18 ++ .../Fixtures/ObjectMapper/VehicleSource.php | 18 ++ .../ObjectMapper/SubtypeObjectMapperTest.php | 152 ++++++++++++++ .../ApiPlatformExtension.php | 4 + .../Resources/config/state/object_mapper.php | 10 + .../MappedDiscriminatedVehicle/MappedCar.php | 25 +++ .../MappedTruck.php | 24 +++ .../MappedVehicle.php | 34 +++ .../MappedDiscriminatedResourceTest.php | 110 ++++++++++ 29 files changed, 965 insertions(+), 3 deletions(-) create mode 100644 src/State/ObjectMapper/SubtypeObjectMapper.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/CarSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/ParentSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php create mode 100644 src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php create mode 100644 src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php create mode 100644 tests/Functional/MappedDiscriminatedResourceTest.php diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 93cdce910b7..4d90993d66f 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -171,6 +171,7 @@ use ApiPlatform\State\CallableProvider; use ApiPlatform\State\DenormalizationViolationFactoryInterface; use ApiPlatform\State\ErrorProvider; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; use ApiPlatform\State\Pagination\Pagination; use ApiPlatform\State\Pagination\PaginationOptions; use ApiPlatform\State\ParameterProviderInterface; @@ -451,7 +452,8 @@ public function register(): void $this->app->extend(ResourceMetadataCollectionFactoryInterface::class, static function (ResourceMetadataCollectionFactoryInterface $inner, Application $app) { return new ObjectMapperMetadataCollectionFactory( $inner, - $app->make(ObjectMapperMetadataFactoryInterface::class) + $app->make(ObjectMapperMetadataFactoryInterface::class), + static fn (): ?SubtypeResolverInterface => self::getSubtypeResolver($app) ); }); } @@ -538,9 +540,15 @@ public function register(): void $this->app->singleton(ObjectMapperMetadataFactoryInterface::class, ReflectionObjectMapperMetadataFactory::class); $this->app->singleton(ObjectMapper::class, static function (Application $app) { - return new ObjectMapper( + $objectMapper = new ObjectMapper( $app->make(ObjectMapperMetadataFactoryInterface::class) ); + + if (!$subtypeResolver = self::getSubtypeResolver($app)) { + return $objectMapper; + } + + return new SubtypeObjectMapper($objectMapper, $subtypeResolver, $app->make(ObjectMapperMetadataFactoryInterface::class)); }); $this->app->extend(ProviderInterface::class, static function (ProviderInterface $inner, Application $app) { diff --git a/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php b/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php index 37204def6a4..8ae8eafd1a5 100644 --- a/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php +++ b/src/Metadata/Resource/Factory/ObjectMapperMetadataCollectionFactory.php @@ -16,14 +16,19 @@ use ApiPlatform\Doctrine\Odm\State\Options as OdmOptions; use ApiPlatform\Doctrine\Orm\State\Options; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; +use ApiPlatform\Metadata\SubtypeResolverInterface; use Symfony\Component\ObjectMapper\Metadata\Mapping; use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; class ObjectMapperMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface { + /** + * @param SubtypeResolverInterface|\Closure(): ?SubtypeResolverInterface|null $subtypeResolver + */ public function __construct( private readonly ResourceMetadataCollectionFactoryInterface $decorated, private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + private SubtypeResolverInterface|\Closure|null $subtypeResolver = null, ) { } @@ -93,7 +98,11 @@ private function canBeMapped(string $class): bool|array { try { $r = new \ReflectionClass($class); - if (!$r->isInstantiable() || !($mapping = $this->objectMapperMetadata->create($r->newInstanceWithoutConstructor(), null, ['_api_check_can_be_mapped' => true]))) { + if (!$r->isInstantiable()) { + return $this->canSubtypesBeMapped($class); + } + + if (!($mapping = $this->objectMapperMetadata->create($r->newInstanceWithoutConstructor(), null, ['_api_check_can_be_mapped' => true]))) { return false; } } catch (\ReflectionException $e) { @@ -102,4 +111,24 @@ private function canBeMapped(string $class): bool|array return $mapping; } + + /** + * @return bool|list + */ + private function canSubtypesBeMapped(string $class): bool|array + { + if ($this->subtypeResolver instanceof \Closure) { + $this->subtypeResolver = ($this->subtypeResolver)(); + } + + $mappings = []; + foreach ($this->subtypeResolver?->getSubtypes($class) ?? [] as $subtype) { + $subtypeMapping = $this->canBeMapped($subtype); + if (\is_array($subtypeMapping)) { + array_push($mappings, ...$subtypeMapping); + } + } + + return $mappings ?: false; + } } diff --git a/src/State/ObjectMapper/SubtypeObjectMapper.php b/src/State/ObjectMapper/SubtypeObjectMapper.php new file mode 100644 index 00000000000..962afb26fff --- /dev/null +++ b/src/State/ObjectMapper/SubtypeObjectMapper.php @@ -0,0 +1,194 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\ObjectMapper; + +use ApiPlatform\Metadata\Exception\RuntimeException; +use ApiPlatform\Metadata\SubtypeResolverInterface; +use Symfony\Component\ObjectMapper\Attribute\Map; +use Symfony\Component\ObjectMapper\Exception\MappingException; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +trait SubtypeObjectMapperTrait +{ + /** @var array */ + private array $abstractCache = []; + /** @var array, 1: list}> */ + private array $candidatesCache = []; + + private function resolveTarget(object $source, object|string|null $target): object|string|null + { + if (!\is_string($target) || !($this->abstractCache[$target] ??= $this->isAbstract($target))) { + return $target; + } + + [$written, $read] = $this->candidatesCache[$source::class.'::'.$target] ??= $this->findCandidates($source, $target); + + $written = $this->filter($written, $source, $target); + $classes = array_values(array_unique(array_column($written, 0))); + if (1 === \count($classes)) { + return $classes[0]; + } + + if ($classes) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": ambiguous target, candidates are "%s".', $source::class, $this->kind($target), $target, implode('", "', $classes))); + } + + $read = $this->filter($read, $source, $target); + if (!$read) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": no subclass of "%s" maps from it.', $source::class, $this->kind($target), $target, $target)); + } + + $survivors = array_filter($read, static function (array $candidate) use ($read): bool { + foreach ($read as $other) { + if ($other[2] !== $candidate[2] && is_subclass_of($other[2], $candidate[2])) { + return false; + } + } + + return true; + }); + $classes = array_values(array_unique(array_column($survivors, 0))); + + if (\count($classes) > 1) { + throw new MappingException(\sprintf('Cannot map "%s" to the %s "%s": ambiguous subclasses, candidates are "%s".', $source::class, $this->kind($target), $target, implode('", "', $classes))); + } + + return $classes[0]; + } + + /** + * @return array{0: list, 1: list} candidates from the mappings of the source then from the subclasses, as [concrete class, "if" condition, mapped source class] + */ + private function findCandidates(object $source, string $target): array + { + $written = []; + foreach ($this->objectMapperMetadata->create($source) as $mapping) { + if (\is_string($mapping->target) && $this->isInstantiable($mapping->target) && is_a($mapping->target, $target, true)) { + $written[] = [$mapping->target, $mapping->if, null]; + } + } + + $read = []; + foreach ($this->subtypeResolver->getSubtypes($target) as $subtype) { + if (!$this->isInstantiable($subtype)) { + continue; + } + + foreach ((new \ReflectionClass($subtype))->getAttributes(Map::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) { + $map = $attribute->newInstance(); + if (\is_string($map->source) && is_a($source, $map->source, true)) { + $read[] = [$subtype, $map->if, $map->source]; + } + } + } + + return [$written, $read]; + } + + /** + * @param list $candidates + * + * @return list + */ + private function filter(array $candidates, object $source, string $abstract): array + { + return array_values(array_filter($candidates, fn (array $candidate): bool => $this->passes($candidate[1], $source, $candidate[0], $candidate[2], $abstract))); + } + + private function passes(mixed $if, object $source, string $target, ?string $mappedSource, string $abstract): bool + { + if (null === $if || true === $if) { + return true; + } + + if (false === $if) { + return false; + } + + if (!\is_callable($if)) { + throw new MappingException(\sprintf('Cannot evaluate the "if" condition of the mapping from "%s" to "%s": service conditions are not supported when mapping to an %s.', $mappedSource ?? $source::class, $target, $this->kind($abstract))); + } + + return \is_string($if) ? (bool) \call_user_func($if, null) : (bool) $if(null, $source, null); + } + + private function kind(string $class): string + { + return interface_exists($class) ? 'interface' : 'abstract class'; + } + + private function isAbstract(string $class): bool + { + return (class_exists($class) || interface_exists($class)) && !(new \ReflectionClass($class))->isInstantiable(); + } + + private function isInstantiable(string $class): bool + { + return class_exists($class) && (new \ReflectionClass($class))->isInstantiable(); + } +} + +if (false === interface_exists(ObjectMapperAwareInterface::class)) { + final class SubtypeObjectMapper implements ObjectMapperInterface + { + use SubtypeObjectMapperTrait; + + public function __construct( + private ObjectMapperInterface $decorated, + private readonly SubtypeResolverInterface $subtypeResolver, + private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + ) { + } + + public function map(object $source, object|string|null $target = null): object + { + return $this->decorated->map($source, $this->resolveTarget($source, $target)); + } + } +} else { + final class SubtypeObjectMapper implements ObjectMapperInterface, ObjectMapperAwareInterface + { + use SubtypeObjectMapperTrait; + + public function __construct( + private ObjectMapperInterface $decorated, + private readonly SubtypeResolverInterface $subtypeResolver, + private readonly ObjectMapperMetadataFactoryInterface $objectMapperMetadata, + ) { + if ($this->decorated instanceof ObjectMapperAwareInterface) { + $this->decorated = $this->decorated->withObjectMapper($this); + } + } + + public function map(object $source, object|string|null $target = null): object + { + return $this->decorated->map($source, $this->resolveTarget($source, $target)); + } + + public function withObjectMapper(ObjectMapperInterface $objectMapper): static + { + $s = clone $this; + + if (!$s->decorated instanceof ObjectMapperAwareInterface) { + throw new RuntimeException(\sprintf('Given object mapper "%s" does not implements %s.', get_debug_type($this->decorated), ObjectMapperAwareInterface::class)); + } + + $s->decorated = $s->decorated->withObjectMapper($objectMapper); + + return $s; + } + } +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php b/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php new file mode 100644 index 00000000000..aa20907457b --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/AbstractMappedTarget.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +abstract class AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php b/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php new file mode 100644 index 00000000000..b72a473cb38 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/AmbiguousWriteSource.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class)] +#[Map(target: SecondConcreteTarget::class)] +final class AmbiguousWriteSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/CarSource.php b/src/State/Tests/Fixtures/ObjectMapper/CarSource.php new file mode 100644 index 00000000000..f1472d5f0df --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/CarSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +class CarSource extends VehicleSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php b/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php new file mode 100644 index 00000000000..ecbb7b3972b --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ConditionalWriteSource.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class, if: [DenyingCondition::class, 'deny'])] +#[Map(target: SecondConcreteTarget::class)] +final class ConditionalWriteSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php b/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php new file mode 100644 index 00000000000..dbb64753d6c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/DenyingCondition.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class DenyingCondition +{ + public static function deny(mixed $value, object $source, ?object $target): bool + { + return false; + } +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php b/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php new file mode 100644 index 00000000000..458e459cabb --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/FirstConcreteTarget.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class FirstConcreteTarget extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php b/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php new file mode 100644 index 00000000000..60329bd0a09 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/InterfaceAndParentSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class InterfaceAndParentSource extends ParentSource implements ReadableSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ParentSource.php b/src/State/Tests/Fixtures/ObjectMapper/ParentSource.php new file mode 100644 index 00000000000..dec212e2c51 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ParentSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +class ParentSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php b/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php new file mode 100644 index 00000000000..88a95658b4d --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ReadableSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +interface ReadableSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php b/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php new file mode 100644 index 00000000000..028b20cbd49 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/SecondConcreteTarget.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class SecondConcreteTarget extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php b/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php new file mode 100644 index 00000000000..3ada58d06c8 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/ServiceConditionSource.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(target: FirstConcreteTarget::class, if: 'app.condition')] +final class ServiceConditionSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php b/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php new file mode 100644 index 00000000000..90b1287adee --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/SportsCarSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class SportsCarSource extends CarSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php b/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php new file mode 100644 index 00000000000..0097dc85b77 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetDeniedFromCar.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: CarSource::class, if: [DenyingCondition::class, 'deny'])] +final class TargetDeniedFromCar extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php new file mode 100644 index 00000000000..16635ab1673 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromCar.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: CarSource::class)] +final class TargetMappedFromCar extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php new file mode 100644 index 00000000000..4160709d45c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: ReadableSource::class)] +final class TargetMappedFromInterface extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php new file mode 100644 index 00000000000..954f9605743 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromParent.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: ParentSource::class)] +final class TargetMappedFromParent extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php new file mode 100644 index 00000000000..7370397439c --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/TargetMappedFromVehicle.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: VehicleSource::class)] +final class TargetMappedFromVehicle extends AbstractMappedTarget +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php b/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php new file mode 100644 index 00000000000..ad6baaf16b7 --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/UnmappedSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +final class UnmappedSource +{ +} diff --git a/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php b/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php new file mode 100644 index 00000000000..0dbde2f086f --- /dev/null +++ b/src/State/Tests/Fixtures/ObjectMapper/VehicleSource.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\Fixtures\ObjectMapper; + +class VehicleSource +{ +} diff --git a/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php b/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php new file mode 100644 index 00000000000..b210ecd0b3d --- /dev/null +++ b/src/State/Tests/ObjectMapper/SubtypeObjectMapperTest.php @@ -0,0 +1,152 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\State\Tests\ObjectMapper; + +use ApiPlatform\Metadata\SubtypeResolverInterface; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\AbstractMappedTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\AmbiguousWriteSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ConditionalWriteSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\FirstConcreteTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\InterfaceAndParentSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ReadableSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\SecondConcreteTarget; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\ServiceConditionSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\SportsCarSource; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetDeniedFromCar; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromCar; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromInterface; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromParent; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\TargetMappedFromVehicle; +use ApiPlatform\State\Tests\Fixtures\ObjectMapper\UnmappedSource; +use PHPUnit\Framework\TestCase; +use Symfony\Component\ObjectMapper\Exception\MappingException; +use Symfony\Component\ObjectMapper\Metadata\Mapping; +use Symfony\Component\ObjectMapper\Metadata\ObjectMapperMetadataFactoryInterface; +use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory; +use Symfony\Component\ObjectMapper\ObjectMapperInterface; + +final class SubtypeObjectMapperTest extends TestCase +{ + public function testAmbiguousWriteTargets(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('"%s", "%s"', FirstConcreteTarget::class, SecondConcreteTarget::class)); + + $this->createMapper($decorated, $resolver)->map(new AmbiguousWriteSource(), AbstractMappedTarget::class); + } + + public function testNoSubclassMapsFromSource(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetMappedFromCar::class]); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot map "%s" to the abstract class "%s": no subclass of "%s" maps from it.', UnmappedSource::class, AbstractMappedTarget::class, AbstractMappedTarget::class)); + + $this->createMapper($decorated, $resolver)->map(new UnmappedSource(), AbstractMappedTarget::class); + } + + public function testClosestParentSourceWins(): void + { + $source = new SportsCarSource(); + $expected = new TargetMappedFromCar(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, TargetMappedFromCar::class)->willReturn($expected); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetMappedFromCar::class]); + + $this->assertSame($expected, $this->createMapper($decorated, $resolver)->map($source, AbstractMappedTarget::class)); + } + + public function testInterfaceAndParentSourcesAreAmbiguous(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromInterface::class, TargetMappedFromParent::class]); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('"%s", "%s"', TargetMappedFromInterface::class, TargetMappedFromParent::class)); + + $this->createMapper($decorated, $resolver)->map(new InterfaceAndParentSource(), AbstractMappedTarget::class); + } + + public function testFalseConditionExcludesWriteCandidate(): void + { + $source = new ConditionalWriteSource(); + $expected = new SecondConcreteTarget(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, SecondConcreteTarget::class)->willReturn($expected); + + $this->assertSame($expected, $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map($source, AbstractMappedTarget::class)); + } + + public function testFalseConditionExcludesReadCandidate(): void + { + $source = new SportsCarSource(); + $expected = new TargetMappedFromVehicle(); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->once())->method('map')->with($source, TargetMappedFromVehicle::class)->willReturn($expected); + $resolver = $this->createStub(SubtypeResolverInterface::class); + $resolver->method('getSubtypes')->willReturn([TargetMappedFromVehicle::class, TargetDeniedFromCar::class]); + + $this->assertSame($expected, $this->createMapper($decorated, $resolver)->map($source, AbstractMappedTarget::class)); + } + + public function testServiceConditionIsRejected(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot evaluate the "if" condition of the mapping from "%s" to "%s": service conditions are not supported when mapping to an abstract class.', ServiceConditionSource::class, FirstConcreteTarget::class)); + + $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map(new ServiceConditionSource(), AbstractMappedTarget::class); + } + + public function testResolutionIsCached(): void + { + $metadata = $this->createMock(ObjectMapperMetadataFactoryInterface::class); + $metadata->expects($this->once())->method('create')->willReturn([new Mapping(FirstConcreteTarget::class)]); + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->exactly(2))->method('map')->with($this->anything(), FirstConcreteTarget::class)->willReturn(new FirstConcreteTarget()); + + $mapper = new SubtypeObjectMapper($decorated, $this->createStub(SubtypeResolverInterface::class), $metadata); + $mapper->map(new UnmappedSource(), AbstractMappedTarget::class); + $mapper->map(new UnmappedSource(), AbstractMappedTarget::class); + } + + public function testInterfaceTargetIsNamedInTheMessage(): void + { + $decorated = $this->createMock(ObjectMapperInterface::class); + $decorated->expects($this->never())->method('map'); + + $this->expectException(MappingException::class); + $this->expectExceptionMessage(\sprintf('Cannot map "%s" to the interface "%s"', UnmappedSource::class, ReadableSource::class)); + + $this->createMapper($decorated, $this->createStub(SubtypeResolverInterface::class))->map(new UnmappedSource(), ReadableSource::class); + } + + private function createMapper(ObjectMapperInterface $decorated, SubtypeResolverInterface $resolver): SubtypeObjectMapper + { + return new SubtypeObjectMapper($decorated, $resolver, new ReflectionObjectMapperMetadataFactory()); + } +} diff --git a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php index 542dfabf2fa..7d0a32dfc5c 100644 --- a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php @@ -215,6 +215,10 @@ public function load(array $configs, ContainerBuilder $container): void if (class_exists(ObjectMapper::class) && ContainerBuilder::willBeAvailable('symfony/object-mapper', ObjectMapperInterface::class, ['symfony/framework-bundle'])) { $loader->load('state/object_mapper.php'); $loader->load($config['use_symfony_listeners'] ? 'symfony/object_mapper.php' : 'state/object_mapper_processor.php'); + + if (!$container->hasDefinition('api_platform.serializer.subtype_resolver')) { + $container->removeDefinition('api_platform.object_mapper.subtype'); + } } $container->setParameter('api_platform.mcp.format', $config['mcp']['format'] ?? null); diff --git a/src/Symfony/Bundle/Resources/config/state/object_mapper.php b/src/Symfony/Bundle/Resources/config/state/object_mapper.php index ad970c8d2d2..74fcafc5750 100644 --- a/src/Symfony/Bundle/Resources/config/state/object_mapper.php +++ b/src/Symfony/Bundle/Resources/config/state/object_mapper.php @@ -15,6 +15,7 @@ use ApiPlatform\Metadata\Resource\Factory\ObjectMapperMetadataCollectionFactory; use ApiPlatform\State\ObjectMapper\ObjectMapper; +use ApiPlatform\State\ObjectMapper\SubtypeObjectMapper; use ApiPlatform\State\Provider\ObjectMapperProvider; use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory; @@ -25,6 +26,14 @@ $services->alias('api_platform.object_mapper', 'object_mapper'); + $services->set('api_platform.object_mapper.subtype', SubtypeObjectMapper::class) + ->decorate('api_platform.object_mapper', null, 0) + ->args([ + service('api_platform.object_mapper.subtype.inner'), + service('api_platform.serializer.subtype_resolver'), + service('api_platform.object_mapper.metadata_factory'), + ]); + $services->set('api_platform.object_mapper.relation', ObjectMapper::class) ->decorate('api_platform.object_mapper', null, -255) ->args([service('api_platform.object_mapper.relation.inner')]); @@ -42,5 +51,6 @@ ->args([ service('api_platform.metadata.resource.metadata_collection_factory.object_mapper.inner'), service('api_platform.object_mapper.metadata_factory'), + service_closure('api_platform.serializer.subtype_resolver')->ignoreOnInvalid(), ]); }; diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php new file mode 100644 index 00000000000..3c4ac4c69f3 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedCar.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDiscriminatedVehicle; + +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: DoctrineDiscriminatedCar::class)] +#[Map(target: DoctrineDiscriminatedCar::class)] +final class MappedCar extends MappedVehicle +{ + public int $seats = 4; + public ?string $vin = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php new file mode 100644 index 00000000000..97e30117fb1 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedTruck.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDiscriminatedVehicle; + +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[Map(source: DoctrineDiscriminatedTruck::class)] +#[Map(target: DoctrineDiscriminatedTruck::class)] +final class MappedTruck extends MappedVehicle +{ + public int $payload = 0; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php new file mode 100644 index 00000000000..535520cba68 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDiscriminatedVehicle/MappedVehicle.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDiscriminatedVehicle; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[ApiResource( + shortName: 'MappedVehicle', + operations: [new Get(), new GetCollection(), new Post()], + stateOptions: new Options(entityClass: DoctrineDiscriminatedVehicle::class), +)] +#[DiscriminatorMap(typeProperty: 'kind', mapping: ['car' => MappedCar::class, 'truck' => MappedTruck::class])] +abstract class MappedVehicle +{ + public ?int $id = null; + public string $name = ''; +} diff --git a/tests/Functional/MappedDiscriminatedResourceTest.php b/tests/Functional/MappedDiscriminatedResourceTest.php new file mode 100644 index 00000000000..dc2e09a1335 --- /dev/null +++ b/tests/Functional/MappedDiscriminatedResourceTest.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDiscriminatedVehicle\MappedVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedSportsCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class MappedDiscriminatedResourceTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DiscriminatorMapAppKernel::class; + } + + public static function getResources(): array + { + return [MappedVehicle::class]; + } + + protected function setUp(): void + { + if ($this->isMongoDB()) { + $this->markTestSkipped('ORM only.'); + } + + $this->recreateSchema([DoctrineDiscriminatedVehicle::class, DoctrineDiscriminatedCar::class, DoctrineDiscriminatedSportsCar::class, DoctrineDiscriminatedTruck::class]); + } + + public function testGetItemMapsEntitySubtypeToResourceSubtype(): void + { + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Volvo'; + $truck->payload = 20000; + $this->persist($truck); + + self::createClient()->request('GET', '/mapped_vehicles/'.$truck->id); + + $this->assertResponseStatusCodeSame(200); + $this->assertJsonContains(['kind' => 'truck', 'name' => 'Volvo', 'payload' => 20000]); + } + + public function testGetCollectionMapsEachItemToItsSubtype(): void + { + $car = new DoctrineDiscriminatedCar(); + $car->name = 'Clio'; + $car->seats = 5; + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Volvo'; + $truck->payload = 20000; + $this->persist($car, $truck); + + self::createClient()->request('GET', '/mapped_vehicles'); + + $this->assertResponseStatusCodeSame(200); + $this->assertJsonContains([ + 'hydra:member' => [ + ['kind' => 'car', 'name' => 'Clio', 'seats' => 5], + ['kind' => 'truck', 'name' => 'Volvo', 'payload' => 20000], + ], + ]); + } + + public function testPostPersistsEntitySubtype(): void + { + self::createClient()->request('POST', '/mapped_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Scania', 'payload' => 3500], + ]); + + $this->assertResponseStatusCodeSame(201); + + $manager = $this->getManager(); + $manager->clear(); + $stored = $manager->getRepository(DoctrineDiscriminatedVehicle::class)->findOneBy(['name' => 'Scania']); + $this->assertInstanceOf(DoctrineDiscriminatedTruck::class, $stored); + $this->assertSame(3500, $stored->payload); + } + + private function persist(object ...$entities): void + { + $manager = $this->getManager(); + foreach ($entities as $entity) { + $manager->persist($entity); + } + $manager->flush(); + $manager->clear(); + } +}