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

api-platform / core / 3712739783

pending completion
3712739783

Pull #5254

github

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

199 of 199 new or added lines in 6 files covered. (100.0%)

7494 of 12363 relevant lines covered (60.62%)

67.55 hits per line

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

0.0
/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
    }
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);
×
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);
×
62
    }
63

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

70
        $options = [];
×
71

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

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

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

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

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

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

98
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
×
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) {
×
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).');
×
114
        }
115

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

121
        foreach ($classMetadata->associationMappings as $association => $mapping) {
×
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)) {
×
124
                continue;
×
125
            }
126

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

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

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

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

159
            if (false === $fetchEager) {
×
160
                continue;
×
161
            }
162

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

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

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

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

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

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

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

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

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

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

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

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

233
            return;
×
234
        }
235

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

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

244
            // If it's an embedded property see below
245
            if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
×
246
                $isFetchable = $propertyMetadata->isFetchable();
×
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())) {
×
249
                    $select[] = $property;
×
250
                }
251

252
                continue;
×
253
            }
254

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

266
        $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
×
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, []);
×
272

273
        if (!\in_array($alias, $existingSelects, true)) {
×
274
            $queryBuilder->addSelect($alias);
×
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