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

api-platform / core / 14008635868

22 Mar 2025 12:39PM UTC coverage: 8.52% (+0.005%) from 8.515%
14008635868

Pull #7042

github

web-flow
Merge fdd88ef56 into 47a6dffbb
Pull Request #7042: Purge parent collections in inheritance cases

4 of 9 new or added lines in 1 file covered. (44.44%)

540 existing lines in 57 files now uncovered.

13394 of 157210 relevant lines covered (8.52%)

22.93 hits per line

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

66.67
/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
    }
762✔
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);
503✔
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);
299✔
61
    }
62

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

69
        $options = [];
762✔
70

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

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

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

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

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

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

97
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
216✔
98
    }
99

100
    /**
101
     * Joins relations to eager load.
102
     *
103
     * @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
104
     * @param int  $joinCount    the number of joins
105
     * @param int  $currentDepth the current max depth
106
     *
107
     * @throws RuntimeException when the max number of joins has been reached
108
     */
109
    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): void
110
    {
111
        if ($joinCount > $this->maxJoins) {
216✔
112
            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).');
×
113
        }
114

115
        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
216✔
116
        $entityManager = $queryBuilder->getEntityManager();
216✔
117
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
216✔
118
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($resourceClass)->getAttributesMetadata();
216✔
119

120
        foreach ($classMetadata->associationMappings as $association => $mapping) {
216✔
121
            // Don't join if max depth is enabled and the current depth limit is reached
122
            if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) {
160✔
123
                continue;
×
124
            }
125

126
            try {
127
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
160✔
128
            } catch (PropertyNotFoundException) {
×
129
                // skip properties not found
130
                continue;
×
131
                // @phpstan-ignore-next-line indeed this can be thrown by the SerializerPropertyMetadataFactory
132
            } catch (ResourceClassNotFoundException) {
×
133
                // skip associations that are not resource classes
134
                continue;
×
135
            }
136

137
            if (
138
                // Always skip extra lazy associations
139
                ClassMetadata::FETCH_EXTRA_LAZY === $mapping['fetch']
160✔
140
                // We don't want to interfere with doctrine on this association
141
                || (false === $forceEager && ClassMetadata::FETCH_EAGER !== $mapping['fetch'])
160✔
142
            ) {
UNCOV
143
                continue;
1✔
144
            }
145

146
            // prepare the child context
147
            $childNormalizationContext = $normalizationContext;
159✔
148
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
159✔
149
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
94✔
UNCOV
150
                    $childNormalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
42✔
151
                }
152
            } else {
153
                $inAttributes = null;
67✔
154
            }
155

156
            $fetchEager = $propertyMetadata->getFetchEager();
159✔
157
            $uriTemplate = $propertyMetadata->getUriTemplate();
159✔
158

159
            if (false === $fetchEager || null !== $uriTemplate) {
159✔
UNCOV
160
                continue;
4✔
161
            }
162

163
            if (true !== $fetchEager && (false === $propertyMetadata->isReadable() || false === $inAttributes)) {
155✔
164
                continue;
140✔
165
            }
166

167
            // Avoid joining back to the parent that we just came from, but only on *ToOne relations
168
            if (
169
                null !== $parentAssociation
93✔
170
                && isset($mapping['inversedBy'])
93✔
171
                && $mapping['sourceEntity'] === $mapping['targetEntity']
93✔
172
                && $mapping['inversedBy'] === $parentAssociation
93✔
173
                && $mapping['type'] & ClassMetadata::TO_ONE
93✔
174
            ) {
175
                continue;
×
176
            }
177

178
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
93✔
179

180
            if (null !== $existingJoin) {
93✔
UNCOV
181
                $associationAlias = $existingJoin->getAlias();
7✔
UNCOV
182
                $isLeftJoin = Join::LEFT_JOIN === $existingJoin->getJoinType();
7✔
183
            } else {
184
                $isNullable = $mapping['joinColumns'][0]?->nullable ?? true;
89✔
185
                $isLeftJoin = false !== $wasLeftJoin || true === $isNullable;
89✔
186
                $method = $isLeftJoin ? 'leftJoin' : 'innerJoin';
89✔
187

188
                $associationAlias = $queryNameGenerator->generateJoinAlias($association);
89✔
189
                $queryBuilder->{$method}(\sprintf('%s.%s', $parentAlias, $association), $associationAlias);
89✔
190
                ++$joinCount;
89✔
191
            }
192

193
            if (true === $fetchPartial) {
93✔
194
                try {
195
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
×
196
                } catch (ResourceClassNotFoundException) {
×
197
                    continue;
×
198
                }
199
            } else {
200
                $this->addSelectOnce($queryBuilder, $associationAlias);
93✔
201
            }
202

203
            // Avoid recursive joins for self-referencing relations
204
            if ($mapping['targetEntity'] === $resourceClass) {
93✔
UNCOV
205
                continue;
4✔
206
            }
207

208
            // Only join the relation's relations recursively if it's a readableLink
209
            if (true !== $fetchEager && (true !== $propertyMetadata->isReadableLink())) {
89✔
210
                continue;
49✔
211
            }
212

UNCOV
213
            if (isset($attributesMetadata[$association])) {
52✔
UNCOV
214
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
52✔
215

216
                // The current depth is the lowest max depth available in the ancestor tree.
UNCOV
217
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
52✔
218
                    $currentDepth = $maxDepth;
×
219
                }
220
            }
221

UNCOV
222
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $childNormalizationContext, $isLeftJoin, $joinCount, $currentDepth, $association);
52✔
223
        }
224
    }
225

226
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions): void
227
    {
228
        $select = [];
×
229
        $entityManager = $queryBuilder->getEntityManager();
×
230
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
×
231
        if (!empty($targetClassMetadata->subClasses)) {
×
232
            $this->addSelectOnce($queryBuilder, $associationAlias);
×
233

234
            return;
×
235
        }
236

237
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
×
238
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
239

240
            if (true === $propertyMetadata->isIdentifier()) {
×
241
                $select[] = $property;
×
242
                continue;
×
243
            }
244

245
            // If it's an embedded property see below
246
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
×
247
                $isFetchable = $propertyMetadata->isFetchable();
×
248
                // the field test allows to add methods to a Resource which do not reflect real database fields
249
                if ($targetClassMetadata->hasField($property) && (true === $isFetchable || $propertyMetadata->isReadable())) {
×
250
                    $select[] = $property;
×
251
                }
252

253
                continue;
×
254
            }
255

256
            // It's an embedded property, select relevant subfields
257
            foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
×
258
                $isFetchable = $propertyMetadata->isFetchable();
×
259
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
260
                $propertyName = "$property.$embeddedProperty";
×
261
                if ($targetClassMetadata->hasField($propertyName) && (true === $isFetchable || $propertyMetadata->isReadable())) {
×
262
                    $select[] = $propertyName;
×
263
                }
264
            }
265
        }
266

267
        $queryBuilder->addSelect(\sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
×
268
    }
269

270
    private function addSelectOnce(QueryBuilder $queryBuilder, string $alias): void
271
    {
272
        $existingSelects = array_reduce($queryBuilder->getDQLPart('select') ?? [], fn ($existing, $dqlSelect) => ($dqlSelect instanceof Select) ? array_merge($existing, $dqlSelect->getParts()) : $existing, []);
93✔
273

274
        if (!\in_array($alias, $existingSelects, true)) {
93✔
275
            $queryBuilder->addSelect($alias);
93✔
276
        }
277
    }
278
}
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

© 2025 Coveralls, Inc