Skip to content

Commit dfb65f5

Browse files
committed
feat(graphql): skip resources with a discriminator map
GraphQL does not support polymorphic resources yet: drop their default GraphQL operations, and throw on explicit `graphQlOperations`.
1 parent 67ad462 commit dfb65f5

10 files changed

Lines changed: 356 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ API Platform 5.1 contains every change shipped in the v5.0.x releases, plus the
88

99
* 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`.
1010
* 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)).
11-
* Resource polymorphism: with `serializer.discriminator_map` enabled (Laravel: `api-platform.serializer.discriminator_map`), the subtypes declared in the serializer `#[DiscriminatorMap]` of a resource, or in its Doctrine discriminator map with `doctrine.discriminator_map` / `doctrine_mongodb_odm.discriminator_map`, are read, written and documented. An update never changes the subtype: a `PUT` or `PATCH` with another type, or a JSON-LD `@type` contradicting the type property, returns a 422. A subtype that is not a resource is named after its class short name in JSON-LD and Hydra: declare it as a resource (e.g. `#[ApiResource(operations: [])]`) to give it another name or `types`. With the Doctrine flags the type property is the discriminator column name, declare a serializer `#[DiscriminatorMap]` on the resource to rename it. Off by default ([#8874](https://github.com/api-platform/core/pull/8874)).
11+
* Resource polymorphism: with `serializer.discriminator_map` enabled (Laravel: `api-platform.serializer.discriminator_map`), the subtypes declared in the serializer `#[DiscriminatorMap]` of a resource, or in its Doctrine discriminator map with `doctrine.discriminator_map` / `doctrine_mongodb_odm.discriminator_map`, are read, written and documented. An update never changes the subtype: a `PUT` or `PATCH` with another type, or a JSON-LD `@type` contradicting the type property, returns a 422. A subtype that is not a resource is named after its class short name in JSON-LD and Hydra: declare it as a resource (e.g. `#[ApiResource(operations: [])]`) to give it another name or `types`. GraphQL is not supported yet for these resources: the default GraphQL operations are dropped, explicit `graphQlOperations` throw. With the Doctrine flags the type property is the discriminator column name, declare a serializer `#[DiscriminatorMap]` on the resource to rename it. Off by default ([#8874](https://github.com/api-platform/core/pull/8874)).
1212
* 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)).
1313
* 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)).
1414

‎src/Laravel/ApiPlatformProvider.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,14 @@ public function register(): void
463463
return new Metadata\Resource\Factory\ParameterResourceMetadataCollectionFactory($inner, $app->make(ModelMetadata::class), new \Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter());
464464
});
465465

466+
$this->app->extend(ResourceMetadataCollectionFactoryInterface::class, static function (ResourceMetadataCollectionFactoryInterface $inner, Application $app) {
467+
if (!$app['config']->get('api-platform.serializer.discriminator_map', false)) {
468+
return $inner;
469+
}
470+
471+
return new Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory(new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), $inner, $app['config']->get('api-platform.defaults', []));
472+
});
473+
466474
$this->app->singleton(OperationMetadataFactory::class, static function (Application $app) {
467475
return new OperationMetadataFactory($app->make(ResourceNameCollectionFactoryInterface::class), $app->make(ResourceMetadataCollectionFactoryInterface::class));
468476
});

‎src/Metadata/Resource/Factory/OperationDefaultsTrait.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,12 @@ private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
149149
$graphQlOperations = [];
150150
foreach ($operations as $operation) {
151151
[$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
152-
$graphQlOperations[$key] = $operation;
152+
$graphQlOperations[$key] = $operation->withExtraProperties($operation->getExtraProperties() + ['graphql_default_operation' => true]);
153153
}
154154

155155
if ($resource->getMercure()) {
156156
[$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
157-
$graphQlOperations[$key] = $operation;
157+
$graphQlOperations[$key] = $operation->withExtraProperties($operation->getExtraProperties() + ['graphql_default_operation' => true]);
158158
}
159159

160160
return $resource->withGraphQlOperations($graphQlOperations);
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
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\Resource\Factory;
15+
16+
use ApiPlatform\Metadata\Exception\RuntimeException;
17+
use ApiPlatform\Metadata\GraphQl\Query;
18+
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
19+
use ApiPlatform\Metadata\Util\CamelCaseToSnakeCaseNameConverter;
20+
use Psr\Log\NullLogger;
21+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
22+
23+
/**
24+
* GraphQL does not support resources with a discriminator map yet: the operations
25+
* added by default are dropped, explicitly declared ones are rejected.
26+
*/
27+
final class PolymorphicGraphQlResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
28+
{
29+
use OperationDefaultsTrait;
30+
31+
public function __construct(
32+
private readonly ClassDiscriminatorResolverInterface $classDiscriminatorResolver,
33+
private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null,
34+
array $defaults = [],
35+
) {
36+
$this->defaults = $defaults;
37+
$this->logger = new NullLogger();
38+
$this->camelCaseToSnakeCaseNameConverter = new CamelCaseToSnakeCaseNameConverter();
39+
}
40+
41+
public function create(string $resourceClass): ResourceMetadataCollection
42+
{
43+
$resourceMetadataCollection = $this->decorated?->create($resourceClass) ?? new ResourceMetadataCollection($resourceClass);
44+
45+
if (!$resourceMetadataCollection->count() || !$this->isPolymorphic($resourceClass)) {
46+
return $resourceMetadataCollection;
47+
}
48+
49+
foreach ($resourceMetadataCollection as $key => $resource) {
50+
$graphQlOperations = [];
51+
$hadDefaults = false;
52+
foreach ($resource->getGraphQlOperations() ?? [] as $name => $operation) {
53+
if ($operation->getExtraProperties()['graphql_default_operation'] ?? false) {
54+
$hadDefaults = true;
55+
continue;
56+
}
57+
58+
if ($operation instanceof Query && $operation->getNested()) {
59+
$graphQlOperations[$name] = $operation;
60+
continue;
61+
}
62+
63+
throw new RuntimeException(\sprintf('GraphQL is not supported yet for "%s", a resource with a discriminator map. Remove its "graphQlOperations" or set them to an empty array.', $resourceClass));
64+
}
65+
66+
if ($hadDefaults) {
67+
$completed = $this->completeGraphQlOperations($resource->withGraphQlOperations($graphQlOperations))->getGraphQlOperations();
68+
foreach ($completed as $name => $operation) {
69+
if (!isset($graphQlOperations[$name])) {
70+
[$name, $operation] = $this->getOperationWithDefaults($resource, $operation);
71+
}
72+
$graphQlOperations[$name] = $operation;
73+
}
74+
}
75+
76+
if ($resource->getGraphQlOperations() !== $graphQlOperations) {
77+
$resourceMetadataCollection[$key] = $resource->withGraphQlOperations($graphQlOperations);
78+
}
79+
}
80+
81+
return $resourceMetadataCollection;
82+
}
83+
84+
private function isPolymorphic(string $resourceClass): bool
85+
{
86+
if (null !== $this->classDiscriminatorResolver->getMappingForClass($resourceClass)) {
87+
return true;
88+
}
89+
90+
foreach (class_parents($resourceClass) ?: [] as $parent) {
91+
if (\in_array($resourceClass, $this->classDiscriminatorResolver->getMappingForClass($parent)?->getTypesMapping() ?? [], true)) {
92+
return true;
93+
}
94+
}
95+
96+
return false;
97+
}
98+
}

‎src/Metadata/Tests/Resource/Factory/AttributesResourceMetadataCollectionFactoryTest.php‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,11 @@ class AttributesResourceMetadataCollectionFactoryTest extends TestCase
6262
private function getDefaultGraphqlOperations(string $shortName, string $class, mixed $provider = null): array
6363
{
6464
return [
65-
'collection_query' => new QueryCollection(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider),
66-
'item_query' => new Query(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider),
67-
'update' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'update', description: "Updates a $shortName.", provider: $provider),
68-
'delete' => new DeleteMutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'delete', description: "Deletes a $shortName.", provider: $provider),
69-
'create' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'create', description: "Creates a $shortName.", provider: $provider),
65+
'collection_query' => new QueryCollection(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider, extraProperties: ['graphql_default_operation' => true]),
66+
'item_query' => new Query(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], provider: $provider, extraProperties: ['graphql_default_operation' => true]),
67+
'update' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'update', description: "Updates a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]),
68+
'delete' => new DeleteMutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'delete', description: "Deletes a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]),
69+
'create' => new Mutation(shortName: $shortName, class: $class, normalizationContext: ['skip_null_values' => true], name: 'create', description: "Creates a $shortName.", provider: $provider, extraProperties: ['graphql_default_operation' => true]),
7070
];
7171
}
7272

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
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\Resource\Factory;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use ApiPlatform\Metadata\Exception\RuntimeException;
18+
use ApiPlatform\Metadata\GraphQl\Query;
19+
use ApiPlatform\Metadata\GraphQl\QueryCollection;
20+
use ApiPlatform\Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory;
21+
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
22+
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
23+
use PHPUnit\Framework\TestCase;
24+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
25+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
26+
27+
final class PolymorphicGraphQlResourceMetadataCollectionFactoryTest extends TestCase
28+
{
29+
public function testDefaultOperationsAreReplacedByNestedOnes(): void
30+
{
31+
$factory = $this->createFactory([
32+
'item_query' => (new Query(name: 'item_query'))->withExtraProperties(['graphql_default_operation' => true]),
33+
'collection_query' => (new QueryCollection(name: 'collection_query'))->withExtraProperties(['graphql_default_operation' => true]),
34+
], true);
35+
36+
$operations = $factory->create(\stdClass::class)[0]->getGraphQlOperations();
37+
38+
$this->assertSame(['item_query', 'collection_query'], array_keys($operations));
39+
$this->assertInstanceOf(QueryCollection::class, $operations['collection_query']);
40+
$this->assertInstanceOf(Query::class, $operations['item_query']);
41+
$this->assertTrue($operations['item_query']->getNested());
42+
$this->assertTrue($operations['collection_query']->getNested());
43+
$this->assertArrayNotHasKey('graphql_default_operation', $operations['item_query']->getExtraProperties());
44+
}
45+
46+
public function testNestedOperationsReceiveTheGlobalDefaults(): void
47+
{
48+
$factory = $this->createFactory(
49+
['item_query' => (new Query(name: 'item_query'))->withExtraProperties(['graphql_default_operation' => true])],
50+
true,
51+
['normalization_context' => ['skip_null_values' => true]]
52+
);
53+
54+
$operations = $factory->create(\stdClass::class)[0]->getGraphQlOperations();
55+
56+
$this->assertSame(['skip_null_values' => true], $operations['collection_query']->getNormalizationContext());
57+
}
58+
59+
public function testExplicitEmptyOperationsAreUntouched(): void
60+
{
61+
$operations = ['item_query' => (new Query(name: 'item_query'))->withNested(true)];
62+
$factory = $this->createFactory($operations, true);
63+
64+
$this->assertSame($operations, $factory->create(\stdClass::class)[0]->getGraphQlOperations());
65+
}
66+
67+
public function testSubtypeResourcesAreDetectedThroughTheirParentMap(): void
68+
{
69+
$decorated = $this->createStub(ResourceMetadataCollectionFactoryInterface::class);
70+
$decorated->method('create')->willReturn(new ResourceMetadataCollection(\UnexpectedValueException::class, [(new ApiResource(class: \UnexpectedValueException::class))->withGraphQlOperations(['item_query' => new Query(name: 'item_query')])]));
71+
72+
$resolver = $this->createStub(ClassDiscriminatorResolverInterface::class);
73+
$resolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => \RuntimeException::class === $class ? new ClassDiscriminatorMapping('kind', ['iterator' => \UnexpectedValueException::class]) : null);
74+
75+
$this->expectException(RuntimeException::class);
76+
77+
(new PolymorphicGraphQlResourceMetadataCollectionFactory($resolver, $decorated))->create(\UnexpectedValueException::class);
78+
}
79+
80+
public function testExplicitOperationsThrow(): void
81+
{
82+
$factory = $this->createFactory(['item_query' => new Query(name: 'item_query')], true);
83+
84+
$this->expectException(RuntimeException::class);
85+
$this->expectExceptionMessage(\sprintf('GraphQL is not supported yet for "%s", a resource with a discriminator map', \stdClass::class));
86+
87+
$factory->create(\stdClass::class);
88+
}
89+
90+
public function testNonPolymorphicResourcesAreUntouched(): void
91+
{
92+
$operations = ['item_query' => new Query(name: 'item_query')];
93+
$factory = $this->createFactory($operations, false);
94+
95+
$this->assertSame($operations, $factory->create(\stdClass::class)[0]->getGraphQlOperations());
96+
}
97+
98+
/**
99+
* @param array<string, Query> $graphQlOperations
100+
*/
101+
private function createFactory(array $graphQlOperations, bool $hasMapping, array $defaults = []): PolymorphicGraphQlResourceMetadataCollectionFactory
102+
{
103+
$decorated = $this->createStub(ResourceMetadataCollectionFactoryInterface::class);
104+
$decorated->method('create')->willReturn(new ResourceMetadataCollection(\stdClass::class, [(new ApiResource(class: \stdClass::class))->withGraphQlOperations($graphQlOperations)]));
105+
106+
$resolver = $this->createStub(ClassDiscriminatorResolverInterface::class);
107+
$resolver->method('getMappingForClass')->willReturn($hasMapping ? new ClassDiscriminatorMapping('kind', ['standard' => \stdClass::class]) : null);
108+
109+
return new PolymorphicGraphQlResourceMetadataCollectionFactory($resolver, $decorated, $defaults);
110+
}
111+
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,9 @@ private function registerMetadataConfiguration(ContainerBuilder $container, arra
504504
$loader->load('metadata/links.php');
505505
$loader->load('metadata/property.php');
506506
$loader->load('metadata/resource.php');
507+
if (!$container->hasDefinition('api_platform.serializer.subtype_resolver')) {
508+
$container->removeDefinition('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql');
509+
}
507510
$loader->load('metadata/operation.php');
508511
$loader->load('metadata/mutator.php');
509512

‎src/Symfony/Bundle/Resources/config/metadata/resource.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
use ApiPlatform\Metadata\Resource\Factory\OperationNameResourceMetadataCollectionFactory;
3030
use ApiPlatform\Metadata\Resource\Factory\ParameterResourceMetadataCollectionFactory;
3131
use ApiPlatform\Metadata\Resource\Factory\PhpFileResourceMetadataCollectionFactory;
32+
use ApiPlatform\Metadata\Resource\Factory\PolymorphicGraphQlResourceMetadataCollectionFactory;
3233
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
3334
use ApiPlatform\Metadata\Resource\Factory\UriTemplateResourceMetadataCollectionFactory;
3435
use ApiPlatform\Symfony\Metadata\Resource\Factory\ContainerParameterResourceMetadataCollectionFactory;
@@ -163,6 +164,14 @@
163164
service('api_platform.resource_class_resolver')->ignoreOnInvalid(),
164165
]);
165166

167+
$services->set('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql', PolymorphicGraphQlResourceMetadataCollectionFactory::class)
168+
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 750)
169+
->args([
170+
service('serializer.mapping.class_discriminator_resolver'),
171+
service('api_platform.metadata.resource.metadata_collection_factory.polymorphic_graphql.inner'),
172+
'%api_platform.defaults%',
173+
]);
174+
166175
$services->set('api_platform.metadata.resource.metadata_collection_factory.cached', CachedResourceMetadataCollectionFactory::class)
167176
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, -10)
168177
->args([

0 commit comments

Comments
 (0)