• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 20745879029

06 Jan 2026 10:43AM UTC coverage: 28.884% (+0.04%) from 28.843%
20745879029

Pull #7647

github

web-flow
Merge 4e69048e9 into d23ab4301
Pull Request #7647: fix(doctrine): fix partial fetch with same entity included multiple time with different fields

32 of 117 new or added lines in 2 files covered. (27.35%)

378 existing lines in 45 files now uncovered.

16832 of 58274 relevant lines covered (28.88%)

78.61 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.91
/src/Doctrine/Orm/Extension/EagerLoadingExtension.php
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\Orm\Extension;
15

16
use ApiPlatform\Doctrine\Orm\Util\QueryBuilderHelper;
17
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
18
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
19
use ApiPlatform\Metadata\Exception\PropertyNotFoundException;
20
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
21
use ApiPlatform\Metadata\Exception\RuntimeException;
22
use ApiPlatform\Metadata\Operation;
23
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use Doctrine\ORM\Mapping\ClassMetadata;
26
use Doctrine\ORM\Query\AST\PartialObjectExpression;
27
use Doctrine\ORM\Query\Expr\Join;
28
use Doctrine\ORM\Query\Expr\Select;
29
use Doctrine\ORM\QueryBuilder;
30
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
31
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
32
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
33
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
34

35
/**
36
 * Eager loads relations.
37
 *
38
 * @author Charles Sarrazin <charles@sarraz.in>
39
 * @author Kévin Dunglas <dunglas@gmail.com>
40
 * @author Antoine Bluchet <soyuka@gmail.com>
41
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
42
 */
43
final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
44
{
45
    public function __construct(private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly int $maxJoins = 30, private readonly bool $forceEager = true, private readonly bool $fetchPartial = false, private readonly ?ClassMetadataFactoryInterface $classMetadataFactory = null)
46
    {
47
    }
876✔
48

49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass = null, ?Operation $operation = null, array $context = []): void
53
    {
54
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
583✔
55
    }
56

57
    /**
58
     * The context may contain serialization groups which helps defining joined entities that are readable.
59
     */
60
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = []): void
61
    {
62
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
338✔
63
    }
64

65
    private function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass, ?Operation $operation, array $context): void
66
    {
67
        if (null === $resourceClass) {
876✔
68
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
×
69
        }
70

71
        $options = [];
876✔
72

73
        $forceEager = $operation?->getForceEager() ?? $this->forceEager;
876✔
74
        $fetchPartial = class_exists(PartialObjectExpression::class) && $operation?->getFetchPartial() ?? $this->fetchPartial;
876✔
75

76
        if (!isset($context['groups']) && !isset($context['attributes'])) {
876✔
77
            $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
649✔
78
            if ($operation) {
649✔
79
                $context += 'denormalization_context' === $contextType ? ($operation->getDenormalizationContext() ?? []) : ($operation->getNormalizationContext() ?? []);
649✔
80
            }
81
        }
82

83
        if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) {
876✔
84
            return;
649✔
85
        }
86

87
        if (!empty($context[AbstractNormalizer::GROUPS])) {
230✔
88
            $options['serializer_groups'] = (array) $context[AbstractNormalizer::GROUPS];
143✔
89
        }
90

91
        if ($operation && $normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null) {
230✔
92
            $options['normalization_groups'] = $normalizationGroups;
137✔
93
        }
94

95
        if ($operation && $denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null) {
230✔
96
            $options['denormalization_groups'] = $denormalizationGroups;
80✔
97
        }
98

99
        $selects = $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
230✔
100
        $selectsByClass = [];
230✔
101
        foreach ($selects as [$entity, $alias, $fields]) {
230✔
102
            if ($entity === $resourceClass) {
103✔
103
                // We don't perform partial select the root entity
104
                $fields = null;
99✔
105
            }
106

107
            if (!isset($selectsByClass[$entity])) {
103✔
108
                $selectsByClass[$entity] = [
103✔
109
                    'aliases' => [$alias => true],
103✔
110
                    'fields' => null === $fields ? null : array_flip($fields),
103✔
111
                ];
103✔
112
            } else {
113
                $selectsByClass[$entity]['aliases'][$alias] = true;
46✔
114
                if (null === $selectsByClass[$entity]['fields']) {
46✔
NEW
115
                    continue;
42✔
116
                }
117

118
                if (null === $fields) {
4✔
NEW
119
                    $selectsByClass[$entity]['fields'] = null;
×
NEW
120
                    continue;
×
121
                }
122

123
                // Merge fields
124
                foreach ($fields as $field) {
4✔
125
                    $selectsByClass[$entity]['fields'][$field] = true;
4✔
126
                }
127
            }
128
        }
129

130
        $existingSelects = [];
230✔
131
        foreach ($queryBuilder->getDQLPart('select') ?? [] as $dqlSelect) {
230✔
132
            if (!$dqlSelect instanceof Select) {
230✔
NEW
133
                continue;
×
134
            }
135
            foreach ($dqlSelect->getParts() as $part) {
230✔
136
                $existingSelects[(string) $part] = true;
230✔
137
            }
138
        }
139

140
        foreach ($selectsByClass as $data) {
230✔
141
            $fields = null === $data['fields'] ? null : array_keys($data['fields']);
103✔
142
            foreach (array_keys($data['aliases']) as $alias) {
103✔
143
                if (isset($existingSelects[$alias])) {
103✔
NEW
144
                    continue;
×
145
                }
146

147
                if (null === $fields) {
103✔
148
                    $queryBuilder->addSelect($alias);
99✔
149
                } else {
150
                    $queryBuilder->addSelect(\sprintf('partial %s.{%s}', $alias, implode(',', $fields)));
4✔
151
                }
152
            }
153
        }
154
    }
155

156
    /**
157
     * Joins relations to eager load.
158
     *
159
     * @param bool $wasLeftJoin  if the relation containing the new one had a left join, we have to force the new one to left join too
160
     * @param int  $joinCount    the number of joins
161
     * @param int  $currentDepth the current max depth
162
     *
163
     * @throws RuntimeException when the max number of joins has been reached
164
     */
165
    private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $options = [], array $normalizationContext = [], bool $wasLeftJoin = false, int &$joinCount = 0, ?int $currentDepth = null, ?string $parentAssociation = null): iterable
166
    {
167
        if ($joinCount > $this->maxJoins) {
230✔
168
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary with the "api_platform.eager_loading.max_joins" configuration key (https://api-platform.com/docs/core/performance/#eager-loading), or limit the maximum serialization depth using the "enable_max_depth" option of the Symfony serializer (https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth).');
×
169
        }
170

171
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
230✔
172
        $entityManager = $queryBuilder->getEntityManager();
230✔
173
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
230✔
174
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($resourceClass)->getAttributesMetadata();
230✔
175

176
        foreach ($classMetadata->associationMappings as $association => $mapping) {
230✔
177
            // Don't join if max depth is enabled and the current depth limit is reached
178
            if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) {
174✔
179
                continue;
×
180
            }
181

182
            try {
183
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
174✔
184
            } catch (PropertyNotFoundException) {
×
185
                // skip properties not found
186
                continue;
×
187
                // @phpstan-ignore-next-line indeed this can be thrown by the SerializerPropertyMetadataFactory
188
            } catch (ResourceClassNotFoundException) {
×
189
                // skip associations that are not resource classes
190
                continue;
×
191
            }
192

193
            if (
194
                // Always skip extra lazy associations
195
                ClassMetadata::FETCH_EXTRA_LAZY === $mapping['fetch']
174✔
196
                // We don't want to interfere with doctrine on this association
197
                || (false === $forceEager && ClassMetadata::FETCH_EAGER !== $mapping['fetch'])
174✔
198
            ) {
199
                continue;
1✔
200
            }
201

202
            // prepare the child context
203
            $childNormalizationContext = $normalizationContext;
173✔
204
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
173✔
205
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
100✔
206
                    $childNormalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
44✔
207
                }
208
            } else {
209
                $inAttributes = null;
75✔
210
            }
211

212
            $fetchEager = $propertyMetadata->getFetchEager();
173✔
213
            $uriTemplate = $propertyMetadata->getUriTemplate();
173✔
214

215
            if (false === $fetchEager || null !== $uriTemplate) {
173✔
216
                continue;
4✔
217
            }
218

219
            if (true !== $fetchEager && (false === $propertyMetadata->isReadable() || false === $inAttributes)) {
169✔
220
                continue;
146✔
221
            }
222

223
            // Avoid joining back to the parent that we just came from, but only on *ToOne relations
224
            if (
225
                null !== $parentAssociation
103✔
226
                && isset($mapping['inversedBy'])
103✔
227
                && $mapping['sourceEntity'] === $mapping['targetEntity']
103✔
228
                && $mapping['inversedBy'] === $parentAssociation
103✔
229
                && $mapping['type'] & ClassMetadata::TO_ONE
103✔
230
            ) {
231
                continue;
×
232
            }
233

234
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
103✔
235

236
            if (null !== $existingJoin) {
103✔
237
                $associationAlias = $existingJoin->getAlias();
9✔
238
                $isLeftJoin = Join::LEFT_JOIN === $existingJoin->getJoinType();
9✔
239
            } else {
240
                $joinColumn = $mapping['joinColumns'][0] ?? ['nullable' => true];
97✔
241
                if (\is_array($joinColumn)) {
97✔
242
                    $isNullable = $joinColumn['nullable'] ?? true;
46✔
243
                } else {
244
                    $isNullable = $joinColumn->nullable ?? true;
73✔
245
                }
246

247
                $isLeftJoin = false !== $wasLeftJoin || true === $isNullable;
97✔
248
                $method = $isLeftJoin ? 'leftJoin' : 'innerJoin';
97✔
249

250
                $associationAlias = $queryNameGenerator->generateJoinAlias($association);
97✔
251
                $queryBuilder->{$method}(\sprintf('%s.%s', $parentAlias, $association), $associationAlias);
97✔
252
                ++$joinCount;
97✔
253
            }
254

255
            if (true === $fetchPartial) {
103✔
256
                try {
257
                    $propertyOptions = $this->getPropertyContext($attributesMetadata[$association] ?? null, $options);
4✔
258
                    yield from $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyOptions);
4✔
259
                } catch (ResourceClassNotFoundException) {
×
260
                    continue;
×
261
                }
262
            } else {
263
                $propertyOptions = null;
99✔
264
                yield [$resourceClass, $associationAlias, null];
99✔
265
            }
266

267
            // Avoid recursive joins for self-referencing relations
268
            if ($mapping['targetEntity'] === $resourceClass) {
103✔
269
                continue;
4✔
270
            }
271

272
            // Only join the relation's relations recursively if it's a readableLink
273
            if (true !== $fetchEager && (true !== $propertyMetadata->isReadableLink())) {
99✔
274
                continue;
55✔
275
            }
276

277
            if (isset($attributesMetadata[$association])) {
56✔
278
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
56✔
279

280
                // The current depth is the lowest max depth available in the ancestor tree.
281
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
56✔
282
                    $currentDepth = $maxDepth;
×
283
                }
284
            }
285

286
            $propertyOptions ??= $this->getPropertyContext($attributesMetadata[$association] ?? null, $options);
56✔
287
            yield from $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyOptions, $childNormalizationContext, $isLeftJoin, $joinCount, $currentDepth, $association);
56✔
288
        }
289
    }
290

291
    private function getPropertyContext(?AttributeMetadataInterface $attributeMetadata, array $options): array
292
    {
293
        if (null === $attributeMetadata) {
60✔
294
            return $options;
×
295
        }
296

297
        $hasNormalizationContext = (isset($options['normalization_groups']) || isset($options['serializer_groups'])) && [] !== $attributeMetadata->getNormalizationContexts();
60✔
298
        $hasDenormalizationContext = (isset($options['denormalization_groups']) || isset($options['serializer_groups'])) && [] !== $attributeMetadata->getDenormalizationContexts();
60✔
299

300
        if (!$hasNormalizationContext && !$hasDenormalizationContext) {
60✔
301
            return $options;
60✔
302
        }
303

304
        $propertyOptions = $options;
4✔
305
        $propertyOptions['normalization_groups'] ??= $options['serializer_groups'];
4✔
306
        $propertyOptions['denormalization_groups'] ??= $options['serializer_groups'];
4✔
307
        // we don't rely on 'serializer_groups' anymore because `context` changes normalization and/or denormalization
308
        // but does not have options for both at the same time
309
        unset($propertyOptions['serializer_groups']);
4✔
310

311
        if ($hasNormalizationContext) {
4✔
312
            $originalGroups = $options['normalization_groups'] ?? $options['serializer_groups'];
4✔
313
            $propertyContext = $attributeMetadata->getNormalizationContextForGroups((array) $originalGroups);
4✔
314
            $propertyOptions['normalization_groups'] = $propertyContext[AbstractNormalizer::GROUPS] ?? $originalGroups;
4✔
315
        }
316
        if ($hasDenormalizationContext) {
4✔
317
            $originalGroups = $options['denormalization_groups'] ?? $options['serializer_groups'];
×
318
            $propertyContext = $attributeMetadata->getDenormalizationContextForGroups((array) $originalGroups);
×
319
            $propertyOptions['denormalization_groups'] = $propertyContext[AbstractNormalizer::GROUPS] ?? $originalGroups;
×
320
        }
321

322
        return $propertyOptions;
4✔
323
    }
324

325
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions): iterable
326
    {
327
        $select = [];
4✔
328
        $entityManager = $queryBuilder->getEntityManager();
4✔
329
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
4✔
330
        if (!empty($targetClassMetadata->subClasses)) {
4✔
NEW
331
            yield [$entity, $associationAlias, null];
×
332

333
            return;
×
334
        }
335

336
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
4✔
337
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
4✔
338

339
            if (true === $propertyMetadata->isIdentifier()) {
4✔
340
                $select[] = $property;
4✔
341
                continue;
4✔
342
            }
343

344
            // If it's an embedded property see below
345
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
4✔
346
                $isFetchable = $propertyMetadata->isFetchable();
4✔
347
                // the field test allows to add methods to a Resource which do not reflect real database fields
348
                if ($targetClassMetadata->hasField($property) && (true === $isFetchable || $propertyMetadata->isReadable())) {
4✔
349
                    $select[] = $property;
4✔
350
                }
351

352
                continue;
4✔
353
            }
354

355
            // It's an embedded property, select relevant subfields
356
            foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
×
357
                $isFetchable = $propertyMetadata->isFetchable();
×
358
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
359
                $propertyName = "$property.$embeddedProperty";
×
360
                if ($targetClassMetadata->hasField($propertyName) && (true === $isFetchable || $propertyMetadata->isReadable())) {
×
361
                    $select[] = $propertyName;
×
362
                }
363
            }
364
        }
365

366
        yield [$entity, $associationAlias, $select];
4✔
367
    }
368
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc