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

api-platform / core / 20712321912

05 Jan 2026 10:20AM UTC coverage: 28.307%. First build
20712321912

Pull #7647

github

web-flow
Merge af83b1e2f into 0e899fa81
Pull Request #7647: Fix partial fetch with same entity included multiple time with different fields

19 of 52 new or added lines in 2 files covered. (36.54%)

16457 of 58137 relevant lines covered (28.31%)

51.3 hits per line

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

64.84
/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\Expr\Join;
27
use Doctrine\ORM\Query\Expr\Select;
28
use Doctrine\ORM\QueryBuilder;
29
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
30
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
31
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
32

33
/**
34
 * Eager loads relations.
35
 *
36
 * @author Charles Sarrazin <charles@sarraz.in>
37
 * @author Kévin Dunglas <dunglas@gmail.com>
38
 * @author Antoine Bluchet <soyuka@gmail.com>
39
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
40
 */
41
final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
42
{
43
    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)
44
    {
45
    }
334✔
46

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

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

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

69
        $options = [];
334✔
70

71
        $forceEager = $operation?->getForceEager() ?? $this->forceEager;
334✔
72
        $fetchPartial = $operation?->getFetchPartial() ?? $this->fetchPartial;
334✔
73

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

81
        if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) {
334✔
82
            return;
306✔
83
        }
84

85
        if (!empty($context[AbstractNormalizer::GROUPS])) {
28✔
86
            $options['serializer_groups'] = (array) $context[AbstractNormalizer::GROUPS];
20✔
87
        }
88

89
        if ($operation && $normalizationGroups = $operation->getNormalizationContext()['groups'] ?? null) {
28✔
90
            $options['normalization_groups'] = $normalizationGroups;
20✔
91
        }
92

93
        if ($operation && $denormalizationGroups = $operation->getDenormalizationContext()['groups'] ?? null) {
28✔
94
            $options['denormalization_groups'] = $denormalizationGroups;
8✔
95
        }
96

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

105
            if (!isset($selectsByClass[$entity])) {
8✔
106
                $selectsByClass[$entity] = [
8✔
107
                    'aliases' => [$alias],
8✔
108
                    'fields' => $fields,
8✔
109
                ];
8✔
110
            } else {
NEW
111
                $selectsByClass[$entity]['aliases'][] = $alias;
×
112
                // If one of the selects for this class is a full select, we don't need partial selects
NEW
113
                if (null === $selectsByClass[$entity]['fields'] || null === $fields) {
×
NEW
114
                    $selectsByClass[$entity]['fields'] = null;
×
NEW
115
                } elseif (null !== $fields) {
×
116
                    // Merge fields
NEW
117
                    $selectsByClass[$entity]['fields'] = array_unique(array_merge($selectsByClass[$entity]['fields'], $fields));
×
118
                }
119
            }
120
        }
121

122
        $existingSelects = array_reduce($queryBuilder->getDQLPart('select') ?? [], fn ($existing, $dqlSelect) => ($dqlSelect instanceof Select) ? array_merge($existing, $dqlSelect->getParts()) : $existing, []);
28✔
123
        foreach ($selectsByClass as $data) {
28✔
124
            foreach (array_unique($data['aliases']) as $alias) {
8✔
125
                if (\in_array($alias, $existingSelects, true)) {
8✔
NEW
126
                    continue;
×
127
                }
128

129
                $fields = $data['fields'];
8✔
130

131
                if (null === $fields) {
8✔
132
                    $queryBuilder->addSelect($alias);
8✔
133
                } else {
NEW
134
                    $queryBuilder->addSelect(sprintf('partial %s.{%s}', $alias, implode(',', $fields)));
×
135
                }
136
            }
137
        }
138
    }
139

140
    /**
141
     * Joins relations to eager load.
142
     *
143
     * @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
144
     * @param int  $joinCount    the number of joins
145
     * @param int  $currentDepth the current max depth
146
     *
147
     * @throws RuntimeException when the max number of joins has been reached
148
     */
149
    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
150
    {
151
        if ($joinCount > $this->maxJoins) {
28✔
152
            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).');
×
153
        }
154

155
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
28✔
156
        $entityManager = $queryBuilder->getEntityManager();
28✔
157
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
28✔
158
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($resourceClass)->getAttributesMetadata();
28✔
159

160
        foreach ($classMetadata->associationMappings as $association => $mapping) {
28✔
161
            // Don't join if max depth is enabled and the current depth limit is reached
162
            if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) {
20✔
163
                continue;
×
164
            }
165

166
            try {
167
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
20✔
168
            } catch (PropertyNotFoundException) {
×
169
                // skip properties not found
170
                continue;
×
171
                // @phpstan-ignore-next-line indeed this can be thrown by the SerializerPropertyMetadataFactory
172
            } catch (ResourceClassNotFoundException) {
×
173
                // skip associations that are not resource classes
174
                continue;
×
175
            }
176

177
            if (
178
                // Always skip extra lazy associations
179
                ClassMetadata::FETCH_EXTRA_LAZY === $mapping['fetch']
20✔
180
                // We don't want to interfere with doctrine on this association
181
                || (false === $forceEager && ClassMetadata::FETCH_EAGER !== $mapping['fetch'])
20✔
182
            ) {
183
                continue;
×
184
            }
185

186
            // prepare the child context
187
            $childNormalizationContext = $normalizationContext;
20✔
188
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
20✔
189
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
8✔
190
                    $childNormalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
2✔
191
                }
192
            } else {
193
                $inAttributes = null;
12✔
194
            }
195

196
            $fetchEager = $propertyMetadata->getFetchEager();
20✔
197
            $uriTemplate = $propertyMetadata->getUriTemplate();
20✔
198

199
            if (false === $fetchEager || null !== $uriTemplate) {
20✔
200
                continue;
×
201
            }
202

203
            if (true !== $fetchEager && (false === $propertyMetadata->isReadable() || false === $inAttributes)) {
20✔
204
                continue;
16✔
205
            }
206

207
            // Avoid joining back to the parent that we just came from, but only on *ToOne relations
208
            if (
209
                null !== $parentAssociation
8✔
210
                && isset($mapping['inversedBy'])
8✔
211
                && $mapping['sourceEntity'] === $mapping['targetEntity']
8✔
212
                && $mapping['inversedBy'] === $parentAssociation
8✔
213
                && $mapping['type'] & ClassMetadata::TO_ONE
8✔
214
            ) {
215
                continue;
×
216
            }
217

218
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
8✔
219

220
            if (null !== $existingJoin) {
8✔
221
                $associationAlias = $existingJoin->getAlias();
2✔
222
                $isLeftJoin = Join::LEFT_JOIN === $existingJoin->getJoinType();
2✔
223
            } else {
224
                $joinColumn = $mapping['joinColumns'][0] ?? ['nullable' => true];
6✔
225
                if (\is_array($joinColumn)) {
6✔
226
                    $isNullable = $joinColumn['nullable'] ?? true;
2✔
227
                } else {
228
                    $isNullable = $joinColumn->nullable ?? true;
4✔
229
                }
230

231
                $isLeftJoin = false !== $wasLeftJoin || true === $isNullable;
6✔
232
                $method = $isLeftJoin ? 'leftJoin' : 'innerJoin';
6✔
233

234
                $associationAlias = $queryNameGenerator->generateJoinAlias($association);
6✔
235
                $queryBuilder->{$method}(\sprintf('%s.%s', $parentAlias, $association), $associationAlias);
6✔
236
                ++$joinCount;
6✔
237
            }
238

239
            if (true === $fetchPartial) {
8✔
240
                try {
NEW
241
                    yield from $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
×
242
                } catch (ResourceClassNotFoundException) {
×
243
                    continue;
×
244
                }
245
            } else {
246
                yield [$resourceClass, $associationAlias, null];
8✔
247
            }
248

249
            // Avoid recursive joins for self-referencing relations
250
            if ($mapping['targetEntity'] === $resourceClass) {
8✔
251
                continue;
×
252
            }
253

254
            // Only join the relation's relations recursively if it's a readableLink
255
            if (true !== $fetchEager && (true !== $propertyMetadata->isReadableLink())) {
8✔
256
                continue;
4✔
257
            }
258

259
            if (isset($attributesMetadata[$association])) {
4✔
260
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
4✔
261

262
                // The current depth is the lowest max depth available in the ancestor tree.
263
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
4✔
264
                    $currentDepth = $maxDepth;
×
265
                }
266
            }
267

268
            yield from $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $childNormalizationContext, $isLeftJoin, $joinCount, $currentDepth, $association);
4✔
269
        }
270
    }
271

272
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions): iterable
273
    {
274
        $select = [];
×
275
        $entityManager = $queryBuilder->getEntityManager();
×
276
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
×
277
        if (!empty($targetClassMetadata->subClasses)) {
×
NEW
278
            yield [$entity, $associationAlias, null];
×
279

280
            return;
×
281
        }
282

283
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
×
284
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
285

286
            if (true === $propertyMetadata->isIdentifier()) {
×
287
                $select[] = $property;
×
288
                continue;
×
289
            }
290

291
            // If it's an embedded property see below
292
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
×
293
                $isFetchable = $propertyMetadata->isFetchable();
×
294
                // the field test allows to add methods to a Resource which do not reflect real database fields
295
                if ($targetClassMetadata->hasField($property) && (true === $isFetchable || $propertyMetadata->isReadable())) {
×
296
                    $select[] = $property;
×
297
                }
298

299
                continue;
×
300
            }
301

302
            // It's an embedded property, select relevant subfields
303
            foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
×
304
                $isFetchable = $propertyMetadata->isFetchable();
×
305
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
306
                $propertyName = "$property.$embeddedProperty";
×
307
                if ($targetClassMetadata->hasField($propertyName) && (true === $isFetchable || $propertyMetadata->isReadable())) {
×
308
                    $select[] = $propertyName;
×
309
                }
310
            }
311
        }
312

NEW
313
        yield [$entity, $associationAlias, $select];
×
314
    }
315
}
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