Skip to content

Commit aff89f0

Browse files
soyukadylan-rumble
andcommitted
feat(doctrine): derive polymorphism from Doctrine
Expose the Doctrine ORM and MongoDB ODM discriminator maps of a resource as serializer discriminator maps with `doctrine.discriminator_map` and `doctrine_mongodb_odm.discriminator_map`. An explicit serializer map takes precedence. Co-authored-by: Dylan van der Hout <dylan@rumble.nl>
1 parent c7555d1 commit aff89f0

29 files changed

Lines changed: 1356 additions & 5 deletions

‎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 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)).
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)).
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

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
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\Doctrine\Common\Serializer\Mapping\Loader;
15+
16+
use ApiPlatform\Metadata\ResourceClassResolverInterface;
17+
use Doctrine\Persistence\ManagerRegistry;
18+
use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
19+
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
20+
use Symfony\Component\Serializer\Mapping\ClassMetadata;
21+
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
22+
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
23+
24+
/**
25+
* Exposes the Doctrine discriminator map (ORM, MongoDB ODM) of a resource hierarchy as a serializer discriminator map.
26+
*
27+
* The serializer does not inherit maps: every class with subclasses gets its own map, so a resource declared in the
28+
* middle of a hierarchy resolves its subtypes too. A serializer map declared in the hierarchy takes precedence.
29+
*
30+
* @internal
31+
*/
32+
final class DoctrineDiscriminatorMappingLoader implements LoaderInterface
33+
{
34+
/** @var array<string, bool> */
35+
private array $serializerDiscriminatorMaps = [];
36+
37+
public function __construct(
38+
private readonly ManagerRegistry $managerRegistry,
39+
private readonly ResourceClassResolverInterface $resourceClassResolver,
40+
private readonly ?LoaderInterface $serializerLoader = null,
41+
) {
42+
}
43+
44+
public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
45+
{
46+
if (null !== $classMetadata->getClassDiscriminatorMapping()) {
47+
return false;
48+
}
49+
50+
$class = $classMetadata->getName();
51+
if (!class_exists($class) || null === $manager = $this->managerRegistry->getManagerForClass($class)) {
52+
return false;
53+
}
54+
55+
$doctrineMetadata = $manager->getClassMetadata($class);
56+
$discriminatorMap = property_exists($doctrineMetadata, 'discriminatorMap') ? $doctrineMetadata->discriminatorMap : null;
57+
if (!\is_array($discriminatorMap) || !$discriminatorMap || null === $typeProperty = $this->getTypeProperty($doctrineMetadata)) {
58+
return false;
59+
}
60+
61+
$typesMapping = [];
62+
$hasSubtypes = false;
63+
foreach ($discriminatorMap as $typeValue => $typeClass) {
64+
if (!\is_string($typeClass) || !is_a($typeClass, $class, true)) {
65+
continue;
66+
}
67+
68+
$typesMapping[(string) $typeValue] = $typeClass;
69+
$hasSubtypes = $hasSubtypes || $typeClass !== $class;
70+
}
71+
72+
// Leaves do not need a map: their type is resolved from the maps of their parents
73+
if (!$hasSubtypes) {
74+
return false;
75+
}
76+
77+
// The root of a hierarchy (e.g. an abstract class) is not necessarily part of the Doctrine map
78+
$hierarchy = array_filter($discriminatorMap, 'is_string');
79+
for ($hierarchyClass = $class; false !== $hierarchyClass; $hierarchyClass = get_parent_class($hierarchyClass)) {
80+
$hierarchy[] = $hierarchyClass;
81+
}
82+
$hierarchy = array_unique($hierarchy);
83+
84+
if (!$this->isResourceHierarchy($hierarchy) || $this->hasSerializerDiscriminatorMap($hierarchy)) {
85+
return false;
86+
}
87+
88+
$defaultType = null;
89+
if (!(new \ReflectionClass($class))->isAbstract() && false !== $ownType = array_search($class, $typesMapping, true)) {
90+
$defaultType = (string) $ownType;
91+
}
92+
93+
$classMetadata->setClassDiscriminatorMapping(new ClassDiscriminatorMapping($typeProperty, $typesMapping, $defaultType));
94+
95+
return true;
96+
}
97+
98+
private function getTypeProperty(object $doctrineMetadata): ?string
99+
{
100+
// ORM: a DiscriminatorColumnMapping object (ORM 3) or an array (ORM 2)
101+
if (property_exists($doctrineMetadata, 'discriminatorColumn') && null !== $column = $doctrineMetadata->discriminatorColumn) {
102+
$name = \is_array($column) ? ($column['name'] ?? null) : ($column->name ?? null);
103+
104+
return \is_string($name) && '' !== $name ? $name : null;
105+
}
106+
107+
if (property_exists($doctrineMetadata, 'discriminatorField') && \is_string($doctrineMetadata->discriminatorField) && '' !== $doctrineMetadata->discriminatorField) {
108+
return $doctrineMetadata->discriminatorField;
109+
}
110+
111+
return null;
112+
}
113+
114+
/**
115+
* @param list<string> $hierarchy
116+
*/
117+
private function isResourceHierarchy(array $hierarchy): bool
118+
{
119+
foreach ($hierarchy as $class) {
120+
if ($this->resourceClassResolver->isResourceClass($class)) {
121+
return true;
122+
}
123+
}
124+
125+
return false;
126+
}
127+
128+
/**
129+
* A serializer map declared anywhere in the hierarchy is the explicit API contract: the Doctrine one is ignored.
130+
*
131+
* @param list<string> $hierarchy
132+
*/
133+
private function hasSerializerDiscriminatorMap(array $hierarchy): bool
134+
{
135+
foreach ($hierarchy as $class) {
136+
if (class_exists($class) && ($this->serializerDiscriminatorMaps[$class] ??= $this->declaresSerializerDiscriminatorMap($class))) {
137+
return true;
138+
}
139+
}
140+
141+
return false;
142+
}
143+
144+
/**
145+
* @param class-string $class
146+
*/
147+
private function declaresSerializerDiscriminatorMap(string $class): bool
148+
{
149+
if (null === $this->serializerLoader) {
150+
return (bool) (new \ReflectionClass($class))->getAttributes(DiscriminatorMap::class, \ReflectionAttribute::IS_INSTANCEOF);
151+
}
152+
153+
$classMetadata = new ClassMetadata($class);
154+
$this->serializerLoader->loadClassMetadata($classMetadata);
155+
156+
return null !== $classMetadata->getClassDiscriminatorMapping();
157+
}
158+
}

0 commit comments

Comments
 (0)