Skip to content

Commit 2ef1b41

Browse files
authored
feat(metadata): add SubtypeResolver (#8883)
Resolve the subtypes of a resource from the serializer discriminator map. Enabled with `serializer.discriminator_map` (Laravel: `api-platform.serializer.discriminator_map`), which is off by default and has no effect on its own yet.
1 parent 68d3133 commit 2ef1b41

11 files changed

Lines changed: 317 additions & 1 deletion

File tree

‎src/Laravel/ApiPlatformProvider.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@
151151
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
152152
use ApiPlatform\Metadata\ResourceClassResolver;
153153
use ApiPlatform\Metadata\ResourceClassResolverInterface;
154+
use ApiPlatform\Metadata\SubtypeResolver;
155+
use ApiPlatform\Metadata\SubtypeResolverInterface;
154156
use ApiPlatform\Metadata\UrlGeneratorInterface;
155157
use ApiPlatform\Metadata\Util\Inflector;
156158
use ApiPlatform\OpenApi\Command\OpenApiCommand;
@@ -217,6 +219,7 @@
217219
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
218220
use Symfony\Component\Routing\RequestContext;
219221
use Symfony\Component\Serializer\Encoder\CsvEncoder;
222+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
220223
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
221224
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
222225
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
@@ -312,6 +315,14 @@ public function register(): void
312315
);
313316
});
314317

318+
$this->app->singleton(SubtypeResolverInterface::class, static function (Application $app) {
319+
return new SubtypeResolver(
320+
new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)),
321+
$app->make(ResourceNameCollectionFactoryInterface::class),
322+
$app->make(ResourceMetadataCollectionFactoryInterface::class),
323+
);
324+
});
325+
315326
$this->app->singleton(SerializerClassMetadataFactory::class, static function (Application $app) {
316327
return new SerializerClassMetadataFactory($app->make(ClassMetadataFactoryInterface::class));
317328
});

‎src/Laravel/config/api-platform.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@
192192

193193
'serializer' => [
194194
'hydra_prefix' => false,
195+
// Read, write and document the subtypes declared in the serializer discriminator map of a resource
196+
'discriminator_map' => false,
195197
// 'datetime_format' => \DateTimeInterface::RFC3339,
196198
],
197199

‎src/Metadata/SubtypeResolver.php‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata;
15+
16+
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
17+
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
18+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
19+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
20+
21+
/**
22+
* @internal
23+
*/
24+
final class SubtypeResolver implements SubtypeResolverInterface
25+
{
26+
/** @var array<string, list<class-string>> */
27+
private array $subtypesCache = [];
28+
/** @var array<class-string, true>|null */
29+
private ?array $resourceClasses = null;
30+
31+
public function __construct(
32+
private readonly ClassDiscriminatorResolverInterface $classDiscriminatorResolver,
33+
private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory,
34+
private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
35+
) {
36+
}
37+
38+
public function getMapping(string $class): ?ClassDiscriminatorMapping
39+
{
40+
return $this->classDiscriminatorResolver->getMappingForClass($class);
41+
}
42+
43+
public function getDirectSubtypes(string $class): array
44+
{
45+
$subtypes = [];
46+
foreach ($this->getMapping($class)?->getTypesMapping() ?? [] as $typeValue => $typeClass) {
47+
if ($typeClass !== $class && is_a($typeClass, $class, true)) {
48+
$subtypes[(string) $typeValue] = $typeClass;
49+
}
50+
}
51+
52+
return $subtypes;
53+
}
54+
55+
public function getSubtypes(string $class): array
56+
{
57+
if (isset($this->subtypesCache[$class])) {
58+
return $this->subtypesCache[$class];
59+
}
60+
61+
$subtypes = [];
62+
foreach ($this->getDirectSubtypes($class) as $subtype) {
63+
$subtypes[$subtype] = $subtype;
64+
foreach ($this->getSubtypes($subtype) as $nestedSubtype) {
65+
$subtypes[$nestedSubtype] = $nestedSubtype;
66+
}
67+
}
68+
69+
return $this->subtypesCache[$class] = array_values($subtypes);
70+
}
71+
72+
public function getTypeName(string $class): string
73+
{
74+
return $this->getResource($class)?->getShortName() ?? $this->getClassShortName($class);
75+
}
76+
77+
public function getTypes(string $class): array
78+
{
79+
if (null === $resource = $this->getResource($class)) {
80+
return [$this->getClassShortName($class)];
81+
}
82+
83+
return $resource->getTypes() ?? [(string) $resource->getShortName()];
84+
}
85+
86+
private function getResource(string $class): ?ApiResource
87+
{
88+
if (null === $this->resourceClasses) {
89+
$this->resourceClasses = [];
90+
foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
91+
$this->resourceClasses[$resourceClass] = true;
92+
}
93+
}
94+
95+
if (!isset($this->resourceClasses[$class])) {
96+
return null;
97+
}
98+
99+
foreach ($this->resourceMetadataCollectionFactory->create($class) as $resource) {
100+
return $resource;
101+
}
102+
103+
return null;
104+
}
105+
106+
private function getClassShortName(string $class): string
107+
{
108+
return false === ($position = strrpos($class, '\\')) ? $class : substr($class, $position + 1);
109+
}
110+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata;
15+
16+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
17+
18+
/**
19+
* Resolves the subtypes a resource exposes through serializer discriminator maps (resource polymorphism).
20+
*
21+
* Only strict subclasses declared in a map are subtypes.
22+
*
23+
* @internal
24+
*/
25+
interface SubtypeResolverInterface
26+
{
27+
public function getMapping(string $class): ?ClassDiscriminatorMapping;
28+
29+
/**
30+
* @return array<string, class-string> the subtypes declared in the map of the class, indexed by type value
31+
*/
32+
public function getDirectSubtypes(string $class): array;
33+
34+
/**
35+
* @return list<class-string> the subtypes declared in the map of the class and, recursively, in the maps of its subtypes
36+
*/
37+
public function getSubtypes(string $class): array;
38+
39+
/**
40+
* Returns the name of a class in JSON-LD and Hydra: the short name of its resource, or of the class.
41+
*/
42+
public function getTypeName(string $class): string;
43+
44+
/**
45+
* Returns the JSON-LD types of a class: the types of its resource, or the short name of the class.
46+
*
47+
* @return list<string>
48+
*/
49+
public function getTypes(string $class): array;
50+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata\Tests;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
18+
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
19+
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
20+
use ApiPlatform\Metadata\Resource\ResourceNameCollection;
21+
use ApiPlatform\Metadata\SubtypeResolver;
22+
use PHPUnit\Framework\TestCase;
23+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
24+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
25+
26+
class SubtypeResolverTest extends TestCase
27+
{
28+
public function testSubtypes(): void
29+
{
30+
$resolver = $this->createResolver();
31+
32+
$this->assertSame(['car' => SubtypeResolverCar::class, 'truck' => SubtypeResolverTruck::class, 'bus' => SubtypeResolverBus::class], $resolver->getDirectSubtypes(SubtypeResolverVehicle::class));
33+
$this->assertSame([SubtypeResolverCar::class, SubtypeResolverTruck::class, SubtypeResolverHeavyTruck::class, SubtypeResolverBus::class], $resolver->getSubtypes(SubtypeResolverVehicle::class));
34+
// A map listing the class itself or an ancestor does not loop
35+
$this->assertSame([SubtypeResolverHeavyTruck::class], $resolver->getSubtypes(SubtypeResolverTruck::class));
36+
}
37+
38+
public function testTypeNames(): void
39+
{
40+
$resolver = $this->createResolver();
41+
42+
$this->assertSame('Vehicle', $resolver->getTypeName(SubtypeResolverVehicle::class));
43+
$this->assertSame(['Vehicle'], $resolver->getTypes(SubtypeResolverVehicle::class));
44+
$this->assertSame('Coach', $resolver->getTypeName(SubtypeResolverBus::class));
45+
$this->assertSame(['https://schema.org/BusOrCoach'], $resolver->getTypes(SubtypeResolverBus::class));
46+
$this->assertSame('SubtypeResolverCar', $resolver->getTypeName(SubtypeResolverCar::class));
47+
$this->assertSame(['SubtypeResolverCar'], $resolver->getTypes(SubtypeResolverCar::class));
48+
}
49+
50+
private function createResolver(): SubtypeResolver
51+
{
52+
$mappings = [
53+
SubtypeResolverVehicle::class => new ClassDiscriminatorMapping('kind', ['car' => SubtypeResolverCar::class, 'truck' => SubtypeResolverTruck::class, 'bus' => SubtypeResolverBus::class]),
54+
SubtypeResolverTruck::class => new ClassDiscriminatorMapping('size', ['vehicle' => SubtypeResolverVehicle::class, 'truck' => SubtypeResolverTruck::class, 'heavy' => SubtypeResolverHeavyTruck::class]),
55+
];
56+
$classDiscriminatorResolver = $this->createStub(ClassDiscriminatorResolverInterface::class);
57+
$classDiscriminatorResolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => $mappings[$class] ?? null);
58+
59+
$resources = [
60+
SubtypeResolverVehicle::class => new ApiResource(shortName: 'Vehicle'),
61+
SubtypeResolverBus::class => new ApiResource(shortName: 'Coach', types: ['https://schema.org/BusOrCoach']),
62+
];
63+
$resourceNameCollectionFactory = $this->createStub(ResourceNameCollectionFactoryInterface::class);
64+
$resourceNameCollectionFactory->method('create')->willReturn(new ResourceNameCollection(array_keys($resources)));
65+
66+
$resourceMetadataCollectionFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class);
67+
$resourceMetadataCollectionFactory->method('create')->willReturnCallback(static fn (string $class): ResourceMetadataCollection => new ResourceMetadataCollection($class, [$resources[$class]]));
68+
69+
return new SubtypeResolver($classDiscriminatorResolver, $resourceNameCollectionFactory, $resourceMetadataCollectionFactory);
70+
}
71+
}
72+
73+
class SubtypeResolverVehicle
74+
{
75+
}
76+
77+
class SubtypeResolverCar extends SubtypeResolverVehicle
78+
{
79+
}
80+
81+
class SubtypeResolverTruck extends SubtypeResolverVehicle
82+
{
83+
}
84+
85+
class SubtypeResolverHeavyTruck extends SubtypeResolverTruck
86+
{
87+
}
88+
89+
class SubtypeResolverBus extends SubtypeResolverVehicle
90+
{
91+
}

‎src/Metadata/composer.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,16 @@
4444
"phpunit/phpunit": "^11.5 || ^12.2 || ^13.0",
4545
"symfony/config": "^7.4 || ^8.0",
4646
"symfony/routing": "^7.4 || ^8.0",
47+
"symfony/serializer": "^7.4 || ^8.0",
4748
"symfony/var-dumper": "^7.4 || ^8.0",
4849
"symfony/web-link": "^7.4 || ^8.0",
4950
"symfony/yaml": "^7.4 || ^8.0"
5051
},
5152
"suggest": {
5253
"phpstan/phpdoc-parser": "For PHP documentation support.",
5354
"symfony/yaml": "For YAML resource configuration.",
54-
"symfony/config": "For XML resource configuration."
55+
"symfony/config": "For XML resource configuration.",
56+
"symfony/serializer": "For resource polymorphism through serializer discriminator maps."
5557
},
5658
"autoload": {
5759
"psr-4": {

‎src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,13 @@ private function registerCommonConfiguration(ContainerBuilder $container, array
349349
$container->setDefinition('serializer.normalizer.number', $numberNormalizerDefinition);
350350
}
351351

352+
if (!$config['serializer']['discriminator_map']) {
353+
$container->removeDefinition('api_platform.serializer.subtype_resolver');
354+
$container->setParameter('api_platform.serializer.resource_polymorphism', false);
355+
} else {
356+
$container->setParameter('api_platform.serializer.resource_polymorphism', true);
357+
}
358+
352359
$defaultContext = ['hydra_prefix' => $config['serializer']['hydra_prefix']] + ($container->hasParameter('serializer.default_context') ? $container->getParameter('serializer.default_context') : []);
353360

354361
$container->setParameter('api_platform.serializer.default_context', $defaultContext);

‎src/Symfony/Bundle/DependencyInjection/Configuration.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ public function getConfigTreeBuilder(): TreeBuilder
173173
->addDefaultsIfNotSet()
174174
->children()
175175
->booleanNode('hydra_prefix')->defaultFalse()->info('Use the "hydra:" prefix.')->end()
176+
->booleanNode('discriminator_map')->defaultFalse()->info('Expose the subtypes declared in the serializer discriminator map of a resource (polymorphic resources): subtype properties are readable, writable and documented.')->end()
176177
->end()
177178
->end()
178179
->end();

‎src/Symfony/Bundle/Resources/config/api.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use ApiPlatform\Metadata\Operation\UnderscorePathSegmentNameGenerator;
2121
use ApiPlatform\Metadata\ResourceClassResolver;
2222
use ApiPlatform\Metadata\ResourceClassResolverInterface;
23+
use ApiPlatform\Metadata\SubtypeResolver;
2324
use ApiPlatform\Metadata\UriVariablesConverter;
2425
use ApiPlatform\Metadata\UriVariableTransformer\ApiResourceUriVariableTransformer;
2526
use ApiPlatform\Metadata\UriVariableTransformer\DateTimeUriVariableTransformer;
@@ -160,6 +161,13 @@
160161
$services->set('api_platform.serializer.operation_resource_resolver', OperationResourceClassResolver::class);
161162
$services->alias(OperationResourceClassResolverInterface::class, 'api_platform.serializer.operation_resource_resolver');
162163

164+
$services->set('api_platform.serializer.subtype_resolver', SubtypeResolver::class)
165+
->args([
166+
service('serializer.mapping.class_discriminator_resolver'),
167+
service('api_platform.metadata.resource.name_collection_factory'),
168+
service('api_platform.metadata.resource.metadata_collection_factory'),
169+
]);
170+
163171
$services->set('api_platform.serializer.normalizer.item', ItemNormalizer::class)
164172
->args([
165173
service('api_platform.metadata.property.name_collection_factory'),

0 commit comments

Comments
 (0)