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

api-platform / core / 15133993414

20 May 2025 09:30AM UTC coverage: 26.313% (-1.2%) from 27.493%
15133993414

Pull #7161

github

web-flow
Merge e2c03d45f into 5459ba375
Pull Request #7161: fix(metadata): infer parameter string type from schema

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

11019 existing lines in 363 files now uncovered.

12898 of 49018 relevant lines covered (26.31%)

34.33 hits per line

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

59.26
/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
    {
UNCOV
45
    }
116✔
46

47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass = null, ?Operation $operation = null, array $context = []): void
51
    {
UNCOV
52
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
104✔
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
    {
UNCOV
60
        $this->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
19✔
61
    }
62

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

UNCOV
69
        $options = [];
116✔
70

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

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

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

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

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

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

UNCOV
97
        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
12✔
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
    {
UNCOV
111
        if ($joinCount > $this->maxJoins) {
12✔
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

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

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

126
            try {
UNCOV
127
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
8✔
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
UNCOV
139
                ClassMetadata::FETCH_EXTRA_LAZY === $mapping['fetch']
8✔
140
                // We don't want to interfere with doctrine on this association
UNCOV
141
                || (false === $forceEager && ClassMetadata::FETCH_EAGER !== $mapping['fetch'])
8✔
142
            ) {
143
                continue;
×
144
            }
145

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

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

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

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

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

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

UNCOV
180
            if (null !== $existingJoin) {
2✔
181
                $associationAlias = $existingJoin->getAlias();
×
182
                $isLeftJoin = Join::LEFT_JOIN === $existingJoin->getJoinType();
×
183
            } else {
UNCOV
184
                $joinColumn = $mapping['joinColumns'][0] ?? ['nullable' => true];
2✔
UNCOV
185
                if (\is_array($joinColumn)) {
2✔
UNCOV
186
                    $isNullable = $joinColumn['nullable'] ?? true;
1✔
187
                } else {
UNCOV
188
                    $isNullable = $joinColumn->nullable ?? true;
1✔
189
                }
190

UNCOV
191
                $isLeftJoin = false !== $wasLeftJoin || true === $isNullable;
2✔
UNCOV
192
                $method = $isLeftJoin ? 'leftJoin' : 'innerJoin';
2✔
193

UNCOV
194
                $associationAlias = $queryNameGenerator->generateJoinAlias($association);
2✔
UNCOV
195
                $queryBuilder->{$method}(\sprintf('%s.%s', $parentAlias, $association), $associationAlias);
2✔
UNCOV
196
                ++$joinCount;
2✔
197
            }
198

UNCOV
199
            if (true === $fetchPartial) {
2✔
200
                try {
201
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
×
202
                } catch (ResourceClassNotFoundException) {
×
203
                    continue;
×
204
                }
205
            } else {
UNCOV
206
                $this->addSelectOnce($queryBuilder, $associationAlias);
2✔
207
            }
208

209
            // Avoid recursive joins for self-referencing relations
UNCOV
210
            if ($mapping['targetEntity'] === $resourceClass) {
2✔
211
                continue;
×
212
            }
213

214
            // Only join the relation's relations recursively if it's a readableLink
UNCOV
215
            if (true !== $fetchEager && (true !== $propertyMetadata->isReadableLink())) {
2✔
UNCOV
216
                continue;
2✔
217
            }
218

219
            if (isset($attributesMetadata[$association])) {
×
220
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();
×
221

222
                // The current depth is the lowest max depth available in the ancestor tree.
223
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
×
224
                    $currentDepth = $maxDepth;
×
225
                }
226
            }
227

228
            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $childNormalizationContext, $isLeftJoin, $joinCount, $currentDepth, $association);
×
229
        }
230
    }
231

232
    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions): void
233
    {
234
        $select = [];
×
235
        $entityManager = $queryBuilder->getEntityManager();
×
236
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
×
237
        if (!empty($targetClassMetadata->subClasses)) {
×
238
            $this->addSelectOnce($queryBuilder, $associationAlias);
×
239

240
            return;
×
241
        }
242

243
        foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
×
244
            $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
×
245

246
            if (true === $propertyMetadata->isIdentifier()) {
×
247
                $select[] = $property;
×
248
                continue;
×
249
            }
250

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

259
                continue;
×
260
            }
261

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

273
        $queryBuilder->addSelect(\sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
×
274
    }
275

276
    private function addSelectOnce(QueryBuilder $queryBuilder, string $alias): void
277
    {
UNCOV
278
        $existingSelects = array_reduce($queryBuilder->getDQLPart('select') ?? [], fn ($existing, $dqlSelect) => ($dqlSelect instanceof Select) ? array_merge($existing, $dqlSelect->getParts()) : $existing, []);
2✔
279

UNCOV
280
        if (!\in_array($alias, $existingSelects, true)) {
2✔
UNCOV
281
            $queryBuilder->addSelect($alias);
2✔
282
        }
283
    }
284
}
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