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

api-platform / core / 7142557150

08 Dec 2023 02:28PM UTC coverage: 36.003% (-1.4%) from 37.36%
7142557150

push

github

web-flow
fix(jsonld): remove link to ApiDocumentation when doc is disabled (#6029)

0 of 1 new or added line in 1 file covered. (0.0%)

2297 existing lines in 182 files now uncovered.

9992 of 27753 relevant lines covered (36.0%)

147.09 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\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
    }
1,587✔
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);
882✔
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);
750✔
62
    }
63

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

70
        $options = [];
1,587✔
71

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

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

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

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

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

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

98
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
576✔
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) {
576✔
UNCOV
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;
576✔
117
        $entityManager = $queryBuilder->getEntityManager();
576✔
118
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
576✔
119
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($resourceClass)->getAttributesMetadata();
576✔
120

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

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

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

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

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

160
            if (false === $fetchEager || null !== $uriTemplate) {
429✔
161
                continue;
12✔
162
            }
163

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

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

179
            $existingJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, $parentAlias, $association);
255✔
180

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

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

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

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

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

214
            if (isset($attributesMetadata[$association])) {
147✔
215
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
147✔
216

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

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

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

UNCOV
235
            return;
×
236
        }
237

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

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

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

UNCOV
254
                continue;
×
255
            }
256

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

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

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

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