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

api-platform / core / 3713134090

pending completion
3713134090

Pull #5254

github

GitHub
Merge b2ec54b3c into ac711530f
Pull Request #5254: [OpenApi] Add ApiResource::openapi and deprecate openapiContext

197 of 197 new or added lines in 5 files covered. (100.0%)

10372 of 12438 relevant lines covered (83.39%)

11.97 hits per line

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

96.12
/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\Exception\InvalidArgumentException;
19
use ApiPlatform\Exception\PropertyNotFoundException;
20
use ApiPlatform\Exception\ResourceClassNotFoundException;
21
use ApiPlatform\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\Mapping\ClassMetadataInfo;
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\Factory\ClassMetadataFactoryInterface;
31
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
32
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
33

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

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

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

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

70
        $options = [];
29✔
71

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

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

82
        if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) {
29✔
83
            return;
8✔
84
        }
85

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

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

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

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

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

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

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

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

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

147
            // prepare the child context
148
            $childNormalizationContext = $normalizationContext;
14✔
149
            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
14✔
150
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
2✔
151
                    $childNormalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
2✔
152
                }
153
            } else {
154
                $inAttributes = null;
12✔
155
            }
156

157
            $fetchEager = $propertyMetadata->getFetchEager();
14✔
158

159
            if (false === $fetchEager) {
14✔
160
                continue;
1✔
161
            }
162

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

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

177
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
12✔
178

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

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

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

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

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

212
            if (isset($attributesMetadata[$association])) {
9✔
213
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
1✔
214

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

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

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

233
            return;
1✔
234
        }
235

236
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
8✔
237
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
7✔
238

239
            if (true === $propertyMetadata->isIdentifier()) {
7✔
240
                $select[] = $property;
5✔
241
                continue;
5✔
242
            }
243

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

252
                continue;
6✔
253
            }
254

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

266
        $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
7✔
267
    }
268

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

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